ngram
listlengths
0
82k
[ "nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout", "1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) +", "nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo =", "= self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank,", "context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) +", "[TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout =", "= 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self,", "label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:,", "sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers,", "import torch import torch.nn as nn from models.neural import MultiHeadedAttention,", "self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1)", "class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__()", "x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank,", "d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model", "nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h", "emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def", "= self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1) context", "def forward(self, iter, query, inputs, mask): if (iter != 0):", "0 hidden_size = hidden_size // num_directions self.relu = nn.ReLU() self.rnn", "0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec", "= 2 if bidirectional else 1 assert hidden_size % num_directions", "self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model,", "dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output)", "pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float()", "inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask)", "bidirectional else 1 assert hidden_size % num_directions == 0 hidden_size", "num_directions == 0 hidden_size = hidden_size // num_directions self.relu =", "x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) #", "PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim)", "x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1)", "inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb", "= PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout =", "else 1 assert hidden_size % num_directions == 0 hidden_size =", "= torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe',", "return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe", "self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout):", "heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model,", "return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout,", "1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__()", "# self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None):", "= nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query,", "self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0):", "emb, step=None): emb = emb * math.sqrt(self.dim) if (step): emb", "return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads,", "= pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim", "num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb", "= top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs", "top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) +", "= d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter", "= nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo", "pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim =", "hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def", "0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs,", "emb = emb + self.pe[:, step][:, None, :] else: emb", "= nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax", "nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR =", "__init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model", "[TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout =", "= self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self,", "emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def", "self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self, emb):", "// num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo", "+ self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module):", "= self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens *", "= self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn)", "self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module):", "edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn", "forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0)", ":n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0)", "/ dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2]", "sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return", "= nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context", "-1) + seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs", "dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward", "def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h)", "else: input_norm = inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm,", "= self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self,", "* hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid()", "self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x)", "edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) # x2", "= self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class", "return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module):", "d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout)", "self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 #", "pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x,", "def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn =", "x + pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i,", "hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True)", "emb * math.sqrt(self.dim) if (step): emb = emb + self.pe[:,", "class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn,", "d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v =", "= self.relu(x2) # x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1),", "batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x", "query, inputs, mask): if (iter != 0): input_norm = self.layer_norm(inputs)", "= PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout)", "sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores", "self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores)", "def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position", "position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float)", "hidden_size // num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size,", "mask[:, :, None].float() x = x + pos_emb for i", "x2 = self.relu(x2) # x2 = self.dropout(x2) # mix =", "self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self,", "self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1)", "bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout =", "edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2 = self.dropout(x2)", "x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) #", "2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float()", "dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1)", "= self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores", "* max_tokens * dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x))", "heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout)", "dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else 1", "1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self,", "seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb", "top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:,", "self.dim = dim def forward(self, emb, step=None): emb = emb", "dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs,", "num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads,", "range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) # all_sents *", "nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents", "MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self,", "__init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model =", "return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel", "= 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout):", "TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder,", "2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer,", "x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1, 1,", "num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if", "edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn,", "* -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() * div_term)", "sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim", "self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout)", "top_vecs * mask[:, :, None].float() x = x + pos_emb", "hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional)", "self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim)", "= hidden_size // num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM(", "x = top_vecs * mask[:, :, None].float() x = x", "self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask):", "edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix,", "PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True)", "syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) # x2 =", "nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi =", "dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2,", "emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads,", "d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU()", "= nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask,", "// num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size,", "x1 = torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank", "def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self,", "d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads,", "num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if", "= LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions *", "n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask =", "max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term", "dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() *", ":n_sents] x = top_vecs * mask[:, :, None].float() x =", "range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo =", "dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden,", "self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def", "eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs, mask):", "n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores", "torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1)", "num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads,", "syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1)", "math import torch import torch.nn as nn from models.neural import", "+ seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs =", "self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 #", "import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1", "!= 0): input_norm = self.layer_norm(inputs) else: input_norm = inputs mask", "self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self,", "self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def", "= x + pos_emb for i in range(self.num_inter_layers): x =", "+ x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank))", "import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def", "self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in", "def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn)", "None].float() x = x + pos_emb for i in range(self.num_inter_layers):", "input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional", "= self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2", "edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn)", "= self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2)", "def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions", "num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout", "= nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if (iter", "class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout", "return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__()", "+ x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores =", "self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn)", "x = torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank", "1, 0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) +", "num_directions = 2 if bidirectional else 1 assert hidden_size %", "self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout,", "self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def", "eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model,", "1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float()", "self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :, None].float() x", "= MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout)", "def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions", "iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask)", "= nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden", "# x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2)", "def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop)", "= nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs,", "= torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1)", "dim, max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1)", "__init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions =", "_ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)", "is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer,", "num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo =", "forward(self, emb, step=None): emb = emb * math.sqrt(self.dim) if (step):", "else: emb = emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb)", "0): input_norm = self.layer_norm(inputs) else: input_norm = inputs mask =", "x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float()", "self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1,", "mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output =", "TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn", ":emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self, emb): return", "inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze(", "# x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2)", "self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x,", "d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers", "dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] =", "self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def", "self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in", "step=None): emb = emb * math.sqrt(self.dim) if (step): emb =", "self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList(", "__init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention(", "nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None): emb =", "emb = self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:,", "d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout)", "0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x", "mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0):", "= nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2", "mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1)", "def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1,", "top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1)", "See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs)", "inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask)", "= nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)])", "nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout", "= self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2", "0 hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size,", "= nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self,", "= dim def forward(self, emb, step=None): emb = emb *", "self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout", "= self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim", "dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model,", "= nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See", "self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim =", "1 assert hidden_size % num_directions == 0 hidden_size = hidden_size", "print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch,", "= num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model,", "bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x,", "nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores =", "pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :,", "max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) /", "div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0)", "# all_sents * max_tokens * dim x = self.layer_norm(x) sent_scores", "dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers =", "range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1,", "Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1)", "self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2)", "self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff,", "= top_vecs * mask[:, :, None].float() x = x +", "class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0):", "(step): emb = emb + self.pe[:, step][:, None, :] else:", "ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module):", "= emb + self.pe[:, step][:, None, :] else: emb =", "self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional)", "nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context =", "bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1,", "nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True)", "dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)", "self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\"", "inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads,", "0::2] = torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() *", "= self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)]", "+ pos_emb for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x,", "if (step): emb = emb + self.pe[:, step][:, None, :]", "torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn", "= self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn)", "h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores", "~mask) # all_sents * max_tokens * dim x = self.layer_norm(x)", "nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None):", "PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout)", "= self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float()", "inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output", "ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class", "= self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class", "TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn", "torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2]", "PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for", "torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim,", "input_norm, mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out) class", "# x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1)", "torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def", "def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs,", "__init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention(", "super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2", "self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1,", "hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 =", "input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out)", "self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for", "self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if", "eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs,", "nn.Softmax(dim=-1) def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\"", "* mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size,", "edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1,", "layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden)", "torch import torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward", "hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else", "sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores", "d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter =", "= nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None): emb", "x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size()", "inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~", "class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__()", "__init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid =", "nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid =", "mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out", "= sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional,", "= nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1,", "input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size,", "TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__()", "syn = self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1,", "d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _", "# syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2", "torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe", "forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out =", "self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\"", "step][:, None, :] else: emb = emb + self.pe[:, :emb.size(1)]", "__init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position =", "__init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions =", "d_model, heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads,", "nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax =", "mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2,", "ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output", "= torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank =", "x = self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens", "(iter != 0): input_norm = self.layer_norm(inputs) else: input_norm = inputs", "def forward(self, emb, step=None): emb = emb * math.sqrt(self.dim) if", ":obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents]", "= torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) *", "top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x = top_vecs *", "class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size,", "torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0)", "import torch.nn as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from", "def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn =", "+ self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb def get_emb(self,", "sent_scores class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class", "= self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc,", "= nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True)", "= self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs", "self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True)", "* mask[:, :, None].float() x = x + pos_emb for", "x, x, ~mask) # all_sents * max_tokens * dim x", "= emb * math.sqrt(self.dim) if (step): emb = emb +", "return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size,", "= torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp((torch.arange(0,", "x = x + pos_emb for i in range(self.num_inter_layers): x", "as nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import", "= self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank,", "return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout,", "mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self,", "RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__()", "-(math.log(10000.0) / dim))) pe[:, 0::2] = torch.sin(position.float() * div_term) pe[:,", "sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim", "self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) * mask.float() return", "mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return", "nn from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter,", "mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _", "nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid()", "nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v", "syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn)", "# sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec =", "sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0):", "self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi = nn.Linear(d_model, d_hidden,", "= torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i", "1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is", "class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder,", "def forward(self, top_vecs, inputs, mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out", "_ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank =", "See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:,", "\"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb =", "heads, d_ff, dropout): super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model,", "* div_term) pe[:, 1::2] = torch.cos(position.float() * div_term) pe =", "= self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim =", "dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm =", "input_norm = inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm,", "sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN,", "self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) #", "x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1, 1, 0)", "class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe = torch.zeros(max_len,", "self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 =", "bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout)", "self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model,", "heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers", "= nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size,", "in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR(", "* math.sqrt(self.dim) if (step): emb = emb + self.pe[:, step][:,", "d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model", "LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 =", "= nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See", "div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout =", "mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel", "eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def", "= inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1,", "self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1,", "edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1,", "from models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class", "num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb", "= nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1)", "mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb", "def get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self,", "= torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores =", "self).__init__() num_directions = 2 if bidirectional else 1 assert hidden_size", "self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2 =", "sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def", "class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder,", "x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores", "def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden", "self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) #", "x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores = sent_scores.squeeze(-1) *", "= sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop):", "= nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout) for _ in range(num_inter_layers)])", "-1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return", "dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq,", "return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff,", "models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__()", "dim def forward(self, emb, step=None): emb = emb * math.sqrt(self.dim)", "\"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch *", "forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn", "self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def", "memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0)", "hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size,", "# self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1,", "for i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask)", "GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def", "torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank)", "0) memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1", "d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc,", "_ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank =", "1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self,", "# x2 = self.relu(x2) # x2 = self.dropout(x2) return syn", "d_ff, dropout) for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm", "= PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self,", "assert hidden_size % num_directions == 0 hidden_size = hidden_size //", "nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def", "self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax =", "self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff, heads,", "\"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out]", ":func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer,", "mask=mask) out = self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module):", "self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model)", "self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module):", "self.transformer_inter[i](i, x, x, ~mask) # all_sents * max_tokens * dim", "div_term = torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim)))", "for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1,", "= torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module):", "bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\" See", "n_sents = top_vecs.size(0), top_vecs.size(1) pos_emb = self.pos_emb.pe[:, :n_sents] x =", "super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else 1 assert", "x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1, edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn =", "input_norm = self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1)", "self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff,", "for _ in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model,", "= self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def __init__(self, d_model, d_ff,", "heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers =", "__init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional,", "edge_weight_2) # x2 = self.relu(x2) # x2 = self.dropout(x2) #", "dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2 if bidirectional else 1", "self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores", "* dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores =", "self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) #", "math.sqrt(self.dim) if (step): emb = emb + self.pe[:, step][:, None,", "mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch", "inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1,", "i in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) #", "hidden_size % num_directions == 0 hidden_size = hidden_size // num_directions", "self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 =", "= num_inter_layers self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model,", ":func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x)", "self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores =", "1, bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self,", "= x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1 = torch.transpose(x1,", "sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000): pe =", "pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout)", "= self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return", "= self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers,", "edge_weight_1) syn=self.relu(syn) syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn =", "hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size,", "mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context)", "out = self.dropout(context) + inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def", "self.pos_emb = PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff,", ":, None].float() x = x + pos_emb for i in", "syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn =", "in range(num_inter_layers)]) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo", "* div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout", "hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1)", "edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) #", "top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores", "edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) #", "x, ~mask) # all_sents * max_tokens * dim x =", "= self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1, 0) #", "mask, label_mask=None): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb =", "nn.Linear(d_model, 1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask):", "syn=self.dropout(syn) syn = self.gcn_x_12(syn, edge_index_1, edge_weight_1) syn = self.relu(syn) syn", "x2 = self.gcn_x_22(mix, edge_index_2, edge_weight_2) # syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) #", "= self.relu(syn) syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2,", "2 if bidirectional else 1 assert hidden_size % num_directions ==", "forward(self, iter, query, inputs, mask): if (iter != 0): input_norm", "memory_bank = torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores =", "+ inputs return self.feed_forward(out) class TransformerInterEncoder(nn.Module): def __init__(self, d_model, d_ff,", "syn = self.dropout(syn) # x2 = self.gcn_x_21(x_1, edge_index_2, edge_weight_2) #", "= torch.transpose(x1, 1, 0) memory_bank, _ = self.rnn(x1) memory_bank =", "None, :] else: emb = emb + self.pe[:, :emb.size(1)] emb", "memory_bank = self.dropout(memory_bank) + x memory_bank = torch.transpose(memory_bank, 1, 0)", "self.layer_norm(inputs) else: input_norm = inputs mask = mask.unsqueeze(1) context =", "nn.Softmax() print('this is dropout',dropout) def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\"", "if (iter != 0): input_norm = self.layer_norm(inputs) else: input_norm =", "torch.transpose(memory_bank, 1, 0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) *", "batch, layer, seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1,", "d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model =", "nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\"", "super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb =", "memory_bank, _ = self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank", "super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else 1 assert", "syn=self.dropout(syn) # x2 = self.relu(x2) # x2 = self.dropout(x2) return", "1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h =", "* layer, -1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank,", "pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1)", "edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2)", "GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout =", "self.dropout = nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask):", "1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores = self.softmax(self.relu(self.wo(memory_bank[:,-1,:])).squeeze(dim=-1).view(-1,layer)).unsqueeze(-1) x=x.transpose(1,2)", "self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs, inputs,", "super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim", ":] else: emb = emb + self.pe[:, :emb.size(1)] emb =", "sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GRUEncoder_attn(nn.Module): def", "forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs,", "dropout): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward", "# syn=self.dropout(syn) # x2 = self.relu(x2) # x2 = self.dropout(x2)", "% num_directions == 0 hidden_size = hidden_size // num_directions self.rnn", "== 0 hidden_size = hidden_size // num_directions self.rnn = LayerNormLSTM(", "= nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x =", "forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" batch, layer, seq, hidden =", "seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i,", "* mask.float() return sent_scores class GCN(nn.Module): def __init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__()", "= self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1)) scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1),", "seq, hidden = x.size() x1=x.contiguous().view(batch * layer, -1, hidden) x1", "= hidden_size // num_directions self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers,", "self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self, emb, step=None):", "sent_scores = sent_scores.squeeze(-1) * mask.float() return sent_scores class GCN(nn.Module): def", "memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank) + x memory_bank", "self.relu(x2) # x2 = self.dropout(x2) # mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2,", "input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size, 1,", "nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden ,", "import math import torch import torch.nn as nn from models.neural", "= nn.Linear(num_directions * hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.sigmoid", "self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1)", "= self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class", "syn=self.gcn_x_12(mix, edge_index_1, edge_weight_1) # syn=self.relu(syn) # syn=self.dropout(syn) # x2 =", "d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model,", "forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0),", "pe = torch.zeros(max_len, dim) position = torch.arange(0, max_len).unsqueeze(1) div_term =", "d_model) self.transformer_inter = nn.ModuleList( [TransformerDecoderLayer(d_model, heads, d_ff, dropout) for _", "forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) *", "top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents = top_vecs.size(0), top_vecs.size(1)", "d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def", "= emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return emb", "self.rnn(x1) memory_bank = self.dropout(memory_bank) + x1 memory_bank = torch.transpose(memory_bank, 1,", "inputs, mask): if (iter != 0): input_norm = self.layer_norm(inputs) else:", "hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid()", "bias=True) self.LR = nn.LeakyReLU() self.softmax = nn.Softmax(dim=-1) def forward(self, top_vecs,", "i in range(self.num_inter_layers): inputs = self.transformer_inter[i](i, top_vecs, inputs,self_attn_mask,~ mask.unsqueeze(1).expand(-1, n_out,-1))", "-1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores = self.softmax(scores) return sent_scores class", "self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x", "def forward(self, top_vecs, mask): \"\"\" See :obj:`EncoderBase.forward()`\"\"\" batch_size, n_sents =", "mask): if (iter != 0): input_norm = self.layer_norm(inputs) else: input_norm", "# mix = self.gcn_mix(torch.cat((syn,x2),-1), edge_index_2, edge_weight_2) # x2 = self.gcn_x_22(mix,", "0) sent_scores = self.sigmoid(self.wo(memory_bank)) sent_scores = sent_scores.squeeze(-1) * mask.float() return", "self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) #", "self.self_attn( ent_enc, ent_enc, context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output", "nn.Dropout(dropout) def forward(self, iter, query, inputs, mask): if (iter !=", "dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid", "super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward =", "nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self, iter, query, inputs,", "= self.pos_emb.pe[:, :n_sents] x = top_vecs * mask[:, :, None].float()", "mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim, max_len=5000):", "self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc, ent_enc, context,", "context, mask=context_attn_mask) dec_output = self.feed_forward(dec_output) return dec_output class TransformerInterDecoder(nn.Module): def", "def __init__(self, d_model, d_ff, heads, dropout, num_inter_layers=0): super(TransformerInterEncoder, self).__init__() self.d_model", "num_directions self.relu = nn.ReLU() self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers,", "def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid", "torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i in", "models.neural import MultiHeadedAttention, PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module):", "MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm", "emb + self.pe[:, step][:, None, :] else: emb = emb", "if bidirectional else 1 assert hidden_size % num_directions == 0", "= nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x, mask_cls):", "iter, query, inputs, mask): if (iter != 0): input_norm =", "= nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True) self.sigmoid =", "self.register_buffer('pe', pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self,", "n_out, -1) + seq_mask), 0) inputs=inputs+pos_emb for i in range(self.num_inter_layers):", "num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers,", "hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax() print('this", "from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier,", "\"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x, 1, 0) memory_bank, _ =", "= torch.exp((torch.arange(0, dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:,", "== 0 hidden_size = hidden_size // num_directions self.relu = nn.ReLU()", "inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out,", "emb = emb + self.pe[:, :emb.size(1)] emb = self.dropout(emb) return", "= PositionalEncoding(dropout, d_model) self.transformer_inter = nn.ModuleList( [TransformerEncoderLayer(d_model, heads, d_ff, dropout)", "nn.Dropout(dropout) self.softmax = nn.Softmax() print('this is dropout',dropout) def forward(self, x,", "self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn(", "hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional else", "LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions * hidden_size,", "sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class", "inputs, self_attn_mask=None,context_attn_mask=None): context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output =", "num_directions == 0 hidden_size = hidden_size // num_directions self.rnn =", "self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim) self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2", "= nn.Dropout(dropout) self.sigmoid = nn.Sigmoid() def forward(self, x, mask): \"\"\"See", ":obj:`EncoderBase.forward()`\"\"\" n_out = inputs.size(1) pos_emb = self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask", "emb = emb * math.sqrt(self.dim) if (step): emb = emb", "-1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _ =", "pe) self.dropout = nn.Dropout(p=dropout) self.dim = dim def forward(self, emb,", "super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0):", "pe[:, 1::2] = torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding,", "sent_scores = self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional,", "= nn.Sigmoid() def forward(self, x, mask_cls): h = self.linear1(x).squeeze(-1) sent_scores", "self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter, ent_enc, inputs, self_attn_mask=None,context_attn_mask=None):", "super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb =", "self.linear1(x).squeeze(-1) sent_scores = self.sigmoid(h) * mask_cls.float() return sent_scores class PositionalEncoding(nn.Module):", "self.softmax(scores) return sent_scores class RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size,", "dim, 2, dtype=torch.float) * -(math.log(10000.0) / dim))) pe[:, 0::2] =", "self.pe[:, step][:, None, :] else: emb = emb + self.pe[:,", "* hidden_size, 1, bias=True) self.dropout = nn.Dropout(dropout) self.softmax = nn.Softmax()", "layer, -1, hidden) x1 = torch.transpose(x1, 1, 0) memory_bank, _", "self.self_attn(input_norm, input_norm, input_norm, mask=mask) out = self.dropout(context) + inputs return", "in range(self.num_inter_layers): x = self.transformer_inter[i](i, x, x, ~mask) # all_sents", "memory_bank = torch.transpose(memory_bank, 1, 0) # sent_scores = self.softmax(self.relu(self.wo(memory_bank)).squeeze(dim=-1)).unsqueeze(-1) sent_scores", "edge_weight_1) syn = self.relu(syn) syn = self.dropout(syn) # x2 =", "= inputs mask = mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm,", "dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.dropout = nn.Dropout(dropout) def forward(self,", "= torch.sin(position.float() * div_term) pe[:, 1::2] = torch.cos(position.float() * div_term)", ", bias=True) self.wi = nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden,", "1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model,", "self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) + seq_mask),", "torch.transpose(x, 1, 0) memory_bank, _ = self.rnn(x) memory_bank = self.dropout(memory_bank)", "= mask.unsqueeze(1) context = self.self_attn(input_norm, input_norm, input_norm, mask=mask) out =", "# x2 = self.relu(x2) # x2 = self.dropout(x2) # mix", "bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2", "max_tokens * dim x = self.layer_norm(x) sent_scores = self.sigmoid(self.wo(x)) sent_scores", "self.rnn = LayerNormLSTM( input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bidirectional=bidirectional) self.wo = nn.Linear(num_directions", "% num_directions == 0 hidden_size = hidden_size // num_directions self.relu", "context = self.self_attn(inputs, inputs, inputs, mask=self_attn_mask) dec_output = self.self_attn( ent_enc,", "bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__() num_directions = 2", "PositionwiseFeedForward from models.rnn import LayerNormLSTM class Classifier(nn.Module): def __init__(self, hidden_size):", "# syn=self.relu(syn) # syn=self.dropout(syn) # x2 = self.relu(x2) # x2", "all_sents * max_tokens * dim x = self.layer_norm(x) sent_scores =", "nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, 1, bias=True)", "hidden_size = hidden_size // num_directions self.relu = nn.ReLU() self.rnn =", "nn.Sigmoid() def forward(self, x, mask): \"\"\"See :func:`EncoderBase.forward()`\"\"\" x = torch.transpose(x,", ":emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff, dropout): super(TransformerEncoderLayer,", "scores=self.v(self.LR( self.wo(inputs.unsqueeze(2)).expand(-1, -1, top_vecs.size(1), -1) + self.wi(top_vecs).unsqueeze( 1))).squeeze(-1) sent_scores =", "x=x.transpose(1,2) sent_vec = torch.matmul(sent_scores.transpose(1,2).unsqueeze(dim = 1).expand(batch,seq,1,layer),x) return sent_vec.squeeze(dim = 2)", "= self.gcn_x_21(x_1, edge_index_2, edge_weight_2) # x2 = self.relu(x2) # x2", "= nn.Linear(d_model, d_hidden, bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR", "d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers", "self).__init__() self.d_model = d_model self.num_inter_layers = num_inter_layers self.pos_emb = PositionalEncoding(dropout,", "bias=True) self.v = nn.Linear(d_hidden, 1, bias=True) self.LR = nn.LeakyReLU() self.softmax", "# self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self, x_1, edge_index_1, edge_index_2=None,edge_weight_1=None,edge_weight_2=None): syn=self.gcn_x_11(x_1, edge_index_1,", "sent_vec.squeeze(dim = 2) class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, heads, d_ff,", "self.dropout(emb) return emb def get_emb(self, emb): return self.pe[:, :emb.size(1)] class", "def __init__(self, d_model, d_ff, heads, dropout, d_hidden, num_inter_layers=0): super(TransformerInterDecoder, self).__init__()", "torch.cos(position.float() * div_term) pe = pe.unsqueeze(0) super(PositionalEncoding, self).__init__() self.register_buffer('pe', pe)", "+ self.pe[:, step][:, None, :] else: emb = emb +", "= self.pos_emb.pe[:, :n_out] seq_mask=subsequent_mask(inputs) self_attn_mask = torch.gt((~label_mask.unsqueeze(1).expand(-1, n_out, -1) +", "dropout, dim, max_len=5000): pe = torch.zeros(max_len, dim) position = torch.arange(0,", "get_emb(self, emb): return self.pe[:, :emb.size(1)] class TransformerEncoderLayer(nn.Module): def __init__(self, d_model,", "__init__(self,in_channel,out_channel,hidden_dim,drop): super(GCN, self).__init__() self.in_channel=in_channel self.out_channel=out_channel self.hidden_dim=hidden_dim self.dropout = nn.Dropout(p=drop) self.gcn_x_11=GCNConv(self.in_channel,self.hidden_dim)", "self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model,", "input_size, hidden_size, dropout=0.0): super(RNNEncoder_attn, self).__init__() num_directions = 2 if bidirectional", "PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm = nn.LayerNorm(d_model, eps=1e-6) def forward(self, iter,", "self.gcn_x_12=GCNConv(self.hidden_dim,self.out_channel)#No.1-*2*2 # self.gcn_x_21=GCNConv(self.in_channel,self.hidden_dim) # self.gcn_x_22=GCNConv(self.hidden_dim,self.out_channel)#No.2-*2 # self.gcn_mix=GCNConv(self.hidden_dim*2,self.hidden_dim)#No.2-*2 self.relu=nn.ReLU(inplace=True) def forward(self,", "1, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, top_vecs, mask): \"\"\"", "= nn.LayerNorm(d_model, eps=1e-6) self.wo = nn.Linear(d_model, d_hidden , bias=True) self.wi", "super(Classifier, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def", "* mask_cls.float() return sent_scores class PositionalEncoding(nn.Module): def __init__(self, dropout, dim,", "heads, d_model, dropout=dropout) self.feed_forward = PositionwiseFeedForward(d_model, d_ff, dropout) self.layer_norm =", "RNNEncoder(nn.Module): def __init__(self, bidirectional, num_layers, input_size, hidden_size, dropout=0.0): super(RNNEncoder, self).__init__()", "class GRUEncoder_attn(nn.Module): def __init__(self,bidirectional, num_layers, input_size, hidden_size,dropout=0.0): super(GRUEncoder_attn,self).__init__() class RNNEncoder_attn(nn.Module):", "super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiHeadedAttention( heads, d_model, dropout=dropout) self.feed_forward =" ]
[ "% (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter)", ") from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id", "requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return", "request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer", "provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url", "( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class", "DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\"", ") response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter) oauth_callback =", "= \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self,", "DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\"", "response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, )", "= requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status()", "app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\"", "import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, )", "def complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url,", "DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url", "OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter):", "= \"https\" def complete_login(self, request, app, token, **kwargs): response =", "complete_login(self, request, app, token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\":", "\"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request,", "authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def", "from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url", "%s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login =", "= \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol =", "(token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter) oauth_callback", "\"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login", "OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id", "access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol", "self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request,", "\"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs):", "\"https\" def complete_login(self, request, app, token, **kwargs): response = requests.post(", "token, **kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" %", "headers={\"Authorization\": \"Bearer %s\" % (token.token,)}, ) response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json())", "OAuth2LoginView, ) from .provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id =", "= DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url =", "**kwargs): response = requests.post( self.profile_url, headers={\"Authorization\": \"Bearer %s\" % (token.token,)},", "redirect_uri_protocol = \"https\" def complete_login(self, request, app, token, **kwargs): response", "requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from", "class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\" authorize_url =", "response.raise_for_status() return self.get_provider().sociallogin_from_response(request, response.json()) oauth_login = OAuth2LoginView.adapter_view(DropboxOAuth2Adapter) oauth_callback = OAuth2CallbackView.adapter_view(DropboxOAuth2Adapter)", "allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import", "\"https://api.dropbox.com/oauth2/token\" authorize_url = \"https://www.dropbox.com/oauth2/authorize\" profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\"", "profile_url = \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app,", ".provider import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url =", "= \"https://api.dropbox.com/2/users/get_current_account\" redirect_uri_protocol = \"https\" def complete_login(self, request, app, token,", "import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import DropboxOAuth2Provider", "from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider", "import DropboxOAuth2Provider class DropboxOAuth2Adapter(OAuth2Adapter): provider_id = DropboxOAuth2Provider.id access_token_url = \"https://api.dropbox.com/oauth2/token\"" ]
[ "# region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region", "# region Options for HTML output # The theme to", "# so a file named \"default.css\" will overwrite the builtin", "configuration # Add any Sphinx extension module names here, as", "for # a list of builtin themes. html_theme = 'alabaster'", "f'v{version}' # endregion # region General configuration # Add any", "with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions", "'<NAME>' # The short X.Y version version = '1.2.7' #", "to this directory. templates_path = ['_templates'] # List of patterns,", "This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] =", "# ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths", "HTML and HTML Help pages. See the documentation for #", "builtin static files, # so a file named \"default.css\" will", "exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion #", "a list of builtin themes. html_theme = 'alabaster' # Add", "'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' # The", "# Add any Sphinx extension module names here, as strings.", "this directory. templates_path = ['_templates'] # List of patterns, relative", "region General configuration # Add any Sphinx extension module names", "sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion #", "that contain templates here, relative to this directory. templates_path =", "# The full version, including alpha/beta/rc tags release = f'v{version}'", "contain templates here, relative to this directory. templates_path = ['_templates']", "for HTML and HTML Help pages. See the documentation for", "files, # so a file named \"default.css\" will overwrite the", "= 'alabaster' # Add any paths that contain custom static", "Add any paths that contain templates here, relative to this", "sheets) here, # relative to this directory. They are copied", "will overwrite the builtin \"default.css\". html_static_path = ['_static'] # endregion", "including alpha/beta/rc tags release = f'v{version}' # endregion # region", "here, relative to this directory. templates_path = ['_templates'] # List", "# The short X.Y version version = '1.2.7' # The", "be # extensions coming with Sphinx (named 'sphinx.ext.*') or your", "pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os", "os.path.abspath('..')) # endregion # region Project information project = 'Upkeep'", "[] master_doc = 'index' # endregion # region Options for", "alpha/beta/rc tags release = f'v{version}' # endregion # region General", "static files, # so a file named \"default.css\" will overwrite", "endregion # region Options for HTML output # The theme", "# relative to this directory. They are copied after the", "typing import Sequence import os import sys # region Path", "theme to use for HTML and HTML Help pages. See", "of builtin themes. html_theme = 'alabaster' # Add any paths", "overwrite the builtin \"default.css\". html_static_path = ['_static'] # endregion #", "They are copied after the builtin static files, # so", "files (such as style sheets) here, # relative to this", "They can be # extensions coming with Sphinx (named 'sphinx.ext.*')", "tags release = f'v{version}' # endregion # region General configuration", "paths that contain custom static files (such as style sheets)", "the builtin static files, # so a file named \"default.css\"", "extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain", "html_theme = 'alabaster' # Add any paths that contain custom", "# region General configuration # Add any Sphinx extension module", "# The theme to use for HTML and HTML Help", "# List of patterns, relative to source directory, that match", "HTML Help pages. See the documentation for # a list", "as strings. They can be # extensions coming with Sphinx", "html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index'", "that contain custom static files (such as style sheets) here,", "author = '<NAME>' # The short X.Y version version =", "relative to this directory. They are copied after the builtin", "# This pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str]", "this directory. They are copied after the builtin static files,", "# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom", "source files. # This pattern also affects html_static_path and html_extra_path.", "= 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>' #", "ignore when looking for source files. # This pattern also", "html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' # endregion", "disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import", "named \"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static']", "contain custom static files (such as style sheets) here, #", "list of builtin themes. html_theme = 'alabaster' # Add any", "Add any Sphinx extension module names here, as strings. They", "= '<NAME>' # The short X.Y version version = '1.2.7'", "extension module names here, as strings. They can be #", "Project information project = 'Upkeep' copyright = '2020, <NAME>' author", "(named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc',", "['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates here,", "'1.2.7' # The full version, including alpha/beta/rc tags release =", "endregion # region Project information project = 'Upkeep' copyright =", "release = f'v{version}' # endregion # region General configuration #", "any Sphinx extension module names here, as strings. They can", "= '1.2.7' # The full version, including alpha/beta/rc tags release", "from typing import Sequence import os import sys # region", "of patterns, relative to source directory, that match files and", "Help pages. See the documentation for # a list of", "import Sequence import os import sys # region Path setup", "here, # relative to this directory. They are copied after", "short X.Y version version = '1.2.7' # The full version,", "the documentation for # a list of builtin themes. html_theme", "'2020, <NAME>' author = '<NAME>' # The short X.Y version", "templates here, relative to this directory. templates_path = ['_templates'] #", "relative to this directory. templates_path = ['_templates'] # List of", "builtin \"default.css\". html_static_path = ['_static'] # endregion # region Extension", "= ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates", "themes. html_theme = 'alabaster' # Add any paths that contain", "SPDX-License-Identifier: MIT # pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import", "custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any", "after the builtin static files, # so a file named", "\"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import sys", "List of patterns, relative to source directory, that match files", "files and # directories to ignore when looking for source", "['_templates'] # List of patterns, relative to source directory, that", "so a file named \"default.css\" will overwrite the builtin \"default.css\".", "X.Y version version = '1.2.7' # The full version, including", "# endregion # region Project information project = 'Upkeep' copyright", "'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative", "directories to ignore when looking for source files. # This", "your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add", "setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project", "to source directory, that match files and # directories to", "version, including alpha/beta/rc tags release = f'v{version}' # endregion #", "any paths that contain custom static files (such as style", "# endregion # region General configuration # Add any Sphinx", "import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion", "# region Project information project = 'Upkeep' copyright = '2020,", "module names here, as strings. They can be # extensions", "any paths that contain templates here, relative to this directory.", "directory. templates_path = ['_templates'] # List of patterns, relative to", "use for HTML and HTML Help pages. See the documentation", "when looking for source files. # This pattern also affects", "file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path =", "'index' # endregion # region Options for HTML output #", "pages. See the documentation for # a list of builtin", "# SPDX-License-Identifier: MIT # pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing", "also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc", "project = 'Upkeep' copyright = '2020, <NAME>' author = '<NAME>'", "General configuration # Add any Sphinx extension module names here,", "patterns, relative to source directory, that match files and #", "Add any paths that contain custom static files (such as", "region Project information project = 'Upkeep' copyright = '2020, <NAME>'", "information project = 'Upkeep' copyright = '2020, <NAME>' author =", "<NAME>' author = '<NAME>' # The short X.Y version version", "a file named \"default.css\" will overwrite the builtin \"default.css\". html_static_path", "https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import os import sys #", "can be # extensions coming with Sphinx (named 'sphinx.ext.*') or", "The short X.Y version version = '1.2.7' # The full", "HTML output # The theme to use for HTML and", "for HTML output # The theme to use for HTML", "builtin themes. html_theme = 'alabaster' # Add any paths that", "(such as style sheets) here, # relative to this directory.", "version = '1.2.7' # The full version, including alpha/beta/rc tags", "# Add any paths that contain custom static files (such", "ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that", "and # directories to ignore when looking for source files.", "'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']", "'alabaster' # Add any paths that contain custom static files", "= 'index' # endregion # region Options for HTML output", "endregion # region General configuration # Add any Sphinx extension", "= f'v{version}' # endregion # region General configuration # Add", "version version = '1.2.7' # The full version, including alpha/beta/rc", "Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions =", "copyright = '2020, <NAME>' author = '<NAME>' # The short", "region Options for HTML output # The theme to use", "pattern also affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = []", "# Add any paths that contain templates here, relative to", "= ['_templates'] # List of patterns, relative to source directory,", "paths that contain templates here, relative to this directory. templates_path", "strings. They can be # extensions coming with Sphinx (named", "coming with Sphinx (named 'sphinx.ext.*') or your custom # ones.", "templates_path = ['_templates'] # List of patterns, relative to source", "are copied after the builtin static files, # so a", "= [] master_doc = 'index' # endregion # region Options", "The full version, including alpha/beta/rc tags release = f'v{version}' #", "output # The theme to use for HTML and HTML", "html_static_path = ['_static'] # endregion # region Extension configuration #", "here, as strings. They can be # extensions coming with", "style sheets) here, # relative to this directory. They are", "copied after the builtin static files, # so a file", "and HTML Help pages. See the documentation for # a", "Options for HTML output # The theme to use for", "os import sys # region Path setup sys.path.insert(0, os.path.abspath('..')) #", "names here, as strings. They can be # extensions coming", "# pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence import", "sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information project =", "The theme to use for HTML and HTML Help pages.", "the builtin \"default.css\". html_static_path = ['_static'] # endregion # region", "custom static files (such as style sheets) here, # relative", "Sequence[str] = [] master_doc = 'index' # endregion # region", "Sequence import os import sys # region Path setup sys.path.insert(0,", "static files (such as style sheets) here, # relative to", "# endregion # region Options for HTML output # The", "and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc = 'index' #", "Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project information", "MIT # pylint: disable=redefined-builtin,invalid-name \"\"\"See https://www.sphinx-doc.org/en/master/usage/configuration.html\"\"\" from typing import Sequence", "for source files. # This pattern also affects html_static_path and", "# directories to ignore when looking for source files. #", "= ['_static'] # endregion # region Extension configuration # endregion", "= '2020, <NAME>' author = '<NAME>' # The short X.Y", "affects html_static_path and html_extra_path. exclude_patterns: Sequence[str] = [] master_doc =", "region Path setup sys.path.insert(0, os.path.abspath('..')) # endregion # region Project", "master_doc = 'index' # endregion # region Options for HTML", "documentation for # a list of builtin themes. html_theme =", "relative to source directory, that match files and # directories", "# a list of builtin themes. html_theme = 'alabaster' #", "that match files and # directories to ignore when looking", "source directory, that match files and # directories to ignore", "Sphinx extension module names here, as strings. They can be", "directory, that match files and # directories to ignore when", "or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] #", "See the documentation for # a list of builtin themes.", "as style sheets) here, # relative to this directory. They", "\"default.css\" will overwrite the builtin \"default.css\". html_static_path = ['_static'] #", "to this directory. They are copied after the builtin static", "to use for HTML and HTML Help pages. See the", "import os import sys # region Path setup sys.path.insert(0, os.path.abspath('..'))", "files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns:", "full version, including alpha/beta/rc tags release = f'v{version}' # endregion", "directory. They are copied after the builtin static files, #", "to ignore when looking for source files. # This pattern", "looking for source files. # This pattern also affects html_static_path", "\"default.css\". html_static_path = ['_static'] # endregion # region Extension configuration", "extensions coming with Sphinx (named 'sphinx.ext.*') or your custom #", "match files and # directories to ignore when looking for" ]
[ "path[path.rfind(\":\") + 1:] if not any(path in type_ for type_", "for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep =", "\"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in", "= list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes", "delete_others=True) print(\"generated in %.2f s\" % (time.time() - t,)) if", "functions = sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return", "join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] =", "single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods", "can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes", "def filter_methods_for_parser_errors(methods): return [m for m in methods if not", "module, header_name, path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP:", "base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated =", "import sys from collections import Counter from collections import defaultdict,", "CppHeaderParser is not thread safe... if skip_macros is None: skip_macros", "= generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others:", "main_classes]) for namespace in namespaces: if not namespace == \"pcl\":", "type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip:", "in modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir)", "header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module,", "nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in", "= [] class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition())", "import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name,", "OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums =", "f in fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool:", "= True if f.get(\"returns_const\"): keep = False for param in", "path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access =", "text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module,", "delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if", "fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] ==", "flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions", "loaders loader_modules = defaultdict(list) for (module, header_name), text in generated_headers.items():", "import defaultdict, OrderedDict from os.path import join from typing import", "type_ in param[\"type\"]: keep = False if keep: filtered.append(f) return", "is not thread safe... if skip_macros is None: skip_macros =", "base_headers headers_to_generate_temp = [] for module, header_name, path in headers_to_generate:", "[] for base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m)", "filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header,", "generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main(): import time", "except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading =", "[m for m in methods if not m[\"name\"] in (\"void\",", "class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\"", "module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if", "= [] if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions,", "SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type", "header_name, path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue", "list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes)", "loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator())", "single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\")", "= join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text):", "filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods", "main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods", "if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read()", "from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree", "keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module,", "relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"):", "module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module,", "base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods =", "variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header,", "methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations =", "for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning:", "time.time() windows = platform.system() == \"Windows\" skip_macros = [] skip_modules", "generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import", "in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if", "[] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"]", "split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def", "(\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m in", "generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str:", "def filter_class_properties(module, header, class_name, properties): key = (module, header, class_name)", "class specialization not implemented for class %s in %s\" print(message", "skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] =", "m in methods) for name, count in count.items(): if count", "def main(): import time t = time.time() windows = platform.system()", "needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules =", "= [] for base, folder, files in os.walk(PATH_MODULES): for f", "in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not in", "header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text =", "specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for type_", "import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition", "generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import", "get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return", "main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in", "header, path, keep_if_no_instantiation=False) return generated_headers def main(): import time t", "Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in methods) for", "in main_classes.items(): classes_by_module[module] += class_ for module, classes in classes_by_module.items():", "headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected", "dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods =", "if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return", "skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions,", "headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE, module,", "= False for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP:", "def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f)", "def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for", "in header.enums if e.get(\"name\")] # skip nameless enums enums =", "main_classes, module_functions, module_variables, module_enums = {}, {}, {}, {} for", "List[CppMethod]: private_defined_outside = [] for m_private in private_methods: for m_outside", "in namespaces: if not namespace == \"pcl\": a(\"using namespace %s;\"", "= v return classes_point_types def make_module_dirs(modules): for module in modules:", "not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors, variables,", "path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations", "message = \"Warning: Template class specialization not implemented for class", "in main_classes]) for namespace in namespaces: if not namespace ==", "module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header,", "platform import shutil import sys from collections import Counter from", "= [(module, header_name, path) for module in modules for header_name,", "elif delete_others: os.remove(path) print(\"Deleted: \" + path) # write new", "class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"]", "= get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class):", "if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for module,", "count in count.items(): if count >= 2: needs.append(name) needs_overloading[module] =", "text in generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name", "Dict, p2: Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\",", "for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods)", "text: loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader", "needs_overloading = {} classes_by_module = defaultdict(list) for (module, _), class_", "module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module)", "generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m in", "\"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"],", "in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"],", "defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module] += class_", "if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules", "def same_parameters(p1: Dict, p2: Dict) -> bool: fields = [\"constant\",", "class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p", "\"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions = sorted(functions,", "\"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True)", "p in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore", "CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions,", "and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods def", "if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = []", "= main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp", "main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header,", "header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside =", "constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module,", "= module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions)", "ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\", m2.get(\"path\")) path", "text = [] if something_instantiated or keep_if_no_instantiation: text = [class_definitions,", "m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else:", "enums enums = sorted(enums, key=lambda v: v[\"name\"]) return enums def", "based on inheritance for module, header in main_classes: main_classes[(module, header)]", "constructors = [] class_def = ClassDefinition(class_, constructors, variables, others, module)", "def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] !=", "True if class_[\"abstract\"]: can_be_instantiated = False else: # check if", "= \"Warning: Template class specialization not implemented for class %s", "pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return", "filtered_properties = [] for p in properties: if p[\"name\"] in", "can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\")", "header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\"))", "and \"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" %", "for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_", "module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others)", "shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for", "= [v for v in header.variables if v.get(\"defaultValue\") and 'using'", "private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"] if", "= make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp)", "!= text: print(\"File is different: %s\" % os.path.split(path)[1]) return True", "-> Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for", "m in methods if not m[\"name\"] in (\"void\", \"bool\")] def", "in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue", "return [m for m in methods if not m[\"name\"] in", "+= base_headers headers_to_generate_temp = [] for module, header_name, path in", "the return type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\")", "continue filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header, module,", "sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for", "get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] =", "keep = False for param in f[\"parameters\"]: for type_ in", "class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties", "[class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module,", "print(\"File is the same: %s\" % os.path.split(path)[1]) return False def", "CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return False #", "%s in %s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name,", "in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] =", "def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be instantiated\"\"\"", "== len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside", "\"union\" in p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"]", "in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\"", "for f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\"", "sort classes inside modules based on inheritance for module, header", "files_to_write = {} for (module, header_name), text in generated_headers.items(): if", "enums = sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path,", "generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module,", "module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] =", "modules = set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) #", "keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers =", "filtered_methods = [] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"])", "!= m2[\"name\"]: return False # bug in CppHeaderParser # in", "[] for module, header_name, path in headers_to_generate: if (module, header_name)", "not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if", "ignore properties without a name properties = [p for p", "needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text = [] a", "= load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def", "for c in classes} for module, header_name in main_classes: for", "m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and", "m not in skip_modules] headers_to_generate = [(module, header_name, path) for", "classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort", "specialization not implemented for class %s in %s\" print(message %", "for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for", "in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"])", "header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_)", "delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict", "header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions =", "main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict", "%s\" % os.path.split(path)[1]) return True # print(\"File is the same:", "if count >= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading", "skip_macros=None): # I tried to do this in multiple threads", "I tried to do this in multiple threads but it", "for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write =", "v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k]", "classes_by_module.items(): needs = [] for class_ in classes: count =", "\"void ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\", m2.get(\"path\"))", "in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods", "(module, _), class_ in main_classes.items(): classes_by_module[module] += class_ for module,", "not None: modules = [m for m in modules if", "if not to_skip: message = \"Warning: Template class specialization not", "continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if", "def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for base,", "c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions = [f for", "parameters for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if", "\"reference\", \"static\"] return all(p1[f] == p2[f] for f in fields)", "if m1[\"name\"] != m2[\"name\"]: return False # bug in CppHeaderParser", "if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return", "classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for module in", "class %s in %s\" print(message % (class_[\"name\"], header_name)) elif (module,", "header_name): # header = read_headers(base_path, header_name, module) main_classes = [c", "(module, header_name), text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name)", "v != text: print(\"File is different: %s\" % os.path.split(path)[1]) return", "for (module, header_name), text in generated_headers.items(): if text: loader_modules[module or", "skip nameless enums enums = sorted(enums, key=lambda v: v[\"name\"]) return", "header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes])", "get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for base, folders,", "\"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key = (module, header,", "<filename>generators/generate_pybind11_bindings.py import os import platform import shutil import sys from", "in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return", "METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) ==", "text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\"))", "class_[\"name\"])) # sort classes inside modules based on inheritance for", "or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES,", "inheritance for module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module,", "return False # same parameters for p1 in m1[\"parameters\"]: for", "import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations", "union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others", "in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore =", "def make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES, module)", "import List, Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser", "collections import Counter from collections import defaultdict, OrderedDict from os.path", "thread safe... if skip_macros is None: skip_macros = [] header_file_str", "module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path,", "{}, {}, {}, {} for module, header_name, path in headers_to_generate[:]:", "filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def", "properties = [p for p in properties if p[\"name\"]] if", "skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers", "= filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods,", "for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types =", "= {} classes_by_module = defaultdict(list) for (module, _), class_ in", "if the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]):", "else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod],", "in main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if", "e.get(\"name\")] # skip nameless enums enums = sorted(enums, key=lambda v:", "header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main():", "ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module,", "-> bool: if m1[\"name\"] != m2[\"name\"]: return False # bug", "+= union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables,", "v return classes_point_types def make_module_dirs(modules): for module in modules: module_dir", "for m in modules if m not in skip_modules] headers_to_generate", "header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name)", "m in modules if m not in skip_modules] headers_to_generate =", "None: modules = MODULES_TO_BUILD if skip_modules is not None: modules", "header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2", "import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class,", "and not \"union\" in p[\"type\"]] union_properties = [p for nested_class", "# hpp files_to_write = {} for (module, header_name), text in", "generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name + \"pp\")", "[p for p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"]", "= defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module] +=", "main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods)", "class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def =", "not \"using\" in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties", "generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types,", "k, v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else:", "headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader]", "class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class:", "in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes", "get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from", "modules for header_name, path in listmod(module)] base_headers = [(\"\", f,", "f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep", "str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside", "= CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return", "= {} for (module, header_name), text in generated_headers.items(): if text:", "import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE,", "FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {}", "is the return type path = m1.get(\"path\", m2.get(\"path\")) path =", "in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties =", "is not None: modules = [m for m in modules", "if not any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]):", "sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions", "not implemented for class %s in %s\" print(message % (class_[\"name\"],", "key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes)", "module, header, path in headers_to_generate for c in main_classes[(module, header)]]", "path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text = []", "param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in", "-> str: header_functions = module_functions[(module, header)] header_classes = main_classes[(module, header)]", "\"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for f in", "module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes", "f in functions: keep = True if f.get(\"returns_const\"): keep =", "instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values()", "text: output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] =", "type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:]", "skip_macros) parser = CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str,", "# sort classes inside modules based on inheritance for module,", "module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function =", "read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False header =", "return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based on", "get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name, module) main_classes", "can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types =", "# in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type", "for m in methods if not m[\"name\"] in (\"void\", \"bool\")]", "same parameters for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]:", "skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path,", "to_skip: message = \"Warning: Template class specialization not implemented for", "SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False if keep:", "m2[\"rtnType\"]]): return False # same parameters for p1 in m1[\"parameters\"]:", "= defaultdict(list) for (module, header_name), text in generated_headers.items(): if text:", "import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types", "OrderedDict from os.path import join from typing import List, Dict,", "header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER)", "for base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for", "private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading:", "main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header,", "= m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not", "\"<\" in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_)", "len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated or keep_if_no_instantiation:", "True # print(\"File is the same: %s\" % os.path.split(path)[1]) return", "in main_classes.values() for c in classes} for module, header_name in", "param[\"type\"]: keep = False if keep: filtered.append(f) return filtered def", "delete_others=True): modules = set(module for module, _ in generated_headers.keys()) make_module_dirs(modules)", "delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict:", "if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class):", "OrderedDict, delete_others=True): modules = set(module for module, _ in generated_headers.keys())", "main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate,", "False header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try:", "in files: path = join(base, f) if path in files_to_write:", "in files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path]) def", "return properties def get_main_classes(header, module, header_name): # header = read_headers(base_path,", "variables = sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header):", "keep_if_no_instantiation=False) return generated_headers def main(): import time t = time.time()", "access = \"private protected public\".split() return set([m[\"name\"] for a in", "methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module),", "def get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name, module)", "in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access", "v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I tried to", "skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in", "if m not in skip_modules] headers_to_generate = [(module, header_name, path)", "if specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for", "import shutil import sys from collections import Counter from collections", "f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers:", "headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers", "v[\"name\"]) return variables def get_enums(header): enums = [e for e", "skip_modules = [] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules", "this in multiple threads but it seems like CppHeaderParser is", "sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def", "base, folder, files in os.walk(PATH_MODULES): for f in files: path", "return variables def get_enums(header): enums = [e for e in", "= [p for p in properties if p[\"name\"]] if key", "import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return", "ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path = m1.get(\"path\",", "in skip_modules] headers_to_generate = [(module, header_name, path) for module in", "not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if", "generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for (module, header_name),", "header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict =", "is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"])", "os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base", "get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros,", "private_defined_outside = [] for m_private in private_methods: for m_outside in", "\"Windows\" skip_macros = [] skip_modules = [] if not windows:", "main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False", "= split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = []", "continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict) ->", "header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\"", "m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1:", "= [] if not windows: skip_macros = [\"_MSC_VER\"] #skip_modules =", "key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions =", "text in files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path])", "generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP,", "[\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\"", "\"pp\") files_to_write[output_path] = text # loaders loader_modules = defaultdict(list) for", "read_header(header_path, skip_macros=None): # I tried to do this in multiple", "in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated", "not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in", "generated_headers = OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module,", "= can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types =", "can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False else: #", "is the same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write,", "False if keep: filtered.append(f) return filtered def get_variables(header): variables =", "== \"Windows\" skip_macros = [] skip_modules = [] if not", "filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in functions: keep", "all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers =", "for module, header, path in headers_to_generate for c in main_classes[(module,", "generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def", "(module, header_name), text in generated_headers.items(): if text: output_path = join(PATH_MODULES,", "else: # check if any pure virtual method is not", "[(module, header_name, path) for module in modules for header_name, path", "filtered_main_classes def get_functions(header, module): functions = [f for f in", "text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces", "module in modules for header_name, path in listmod(module)] base_headers =", "all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types", "header, class_name, properties): key = (module, header, class_name) # ignore", "[\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for", "def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module, _", "[v for v in header.variables if v.get(\"defaultValue\") and 'using' !=", "base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class)", "%s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in", "for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods", "methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"] if not", "collections import defaultdict, OrderedDict from os.path import join from typing", "in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class)", "parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError:", "def get_variables(header): variables = [v for v in header.variables if", "same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name,", "not thread safe... if skip_macros is None: skip_macros = []", "path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif", "from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\", "= {}, {}, {}, {} for module, header_name, path in", "keep = False if keep: filtered.append(f) return filtered def get_variables(header):", "path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path, keep_if_no_instantiation=False)", "key = (module, header, class_name) # ignore properties without a", "= text # loaders loader_modules = defaultdict(list) for (module, header_name),", "write_if_different(files_to_write, delete_others): written = [] for base, folder, files in", "written = [] for base, folder, files in os.walk(PATH_MODULES): for", "[] for p in properties: if p[\"name\"] in to_ignore: continue", "methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods +=", "files: path = join(base, f) if path in files_to_write: if", "bool: if m1[\"name\"] != m2[\"name\"]: return False # bug in", "return classes_point_types def make_module_dirs(modules): for module in modules: module_dir =", "header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def", "to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header,", "filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered =", "= False header = parser.CppHeader(header_file_str, argType=\"string\") return header def clean():", "join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name) header =", "not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = []", "a name properties = [p for p in properties if", "generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first =", "header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading", "folder, files in os.walk(PATH_MODULES): for f in files: path =", "variables = [v for v in header.variables if v.get(\"defaultValue\") and", "m_private in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside):", "class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not", "methods) for name, count in count.items(): if count >= 2:", "os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading", "written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path) # write", "print(\"Deleted: \" + path) # write new files for path,", "m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else: return False", "a in access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]])", "filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in", "= generate_header(module, header, path, keep_if_no_instantiation=False) return generated_headers def main(): import", "type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template", "def get_functions(header, module): functions = [f for f in header.functions", "for v in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')]", "nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties)", "= class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties =", "others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors =", "if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module,", "class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors, variables, others,", "nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties =", "filter_methods_for_parser_errors(methods): return [m for m in methods if not m[\"name\"]", "for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return", "in access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def", "List[CppMethod]) -> str: text = [] a = text.append a(common_includes)", "\"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c", "in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def", "in classes_by_module.items(): needs = [] for class_ in classes: count", "= list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading =", "needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = [] for", "import os import platform import shutil import sys from collections", "in headers_to_generate for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes)", "= False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\",", "module, header_name + \"pp\") files_to_write[output_path] = text # loaders loader_modules", "m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument and", "namespace == \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for", "f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp =", "m2[\"name\"] and same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"])", "[p for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if", "module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) >", "p2[f] for f in fields) def same_methods(m1: CppMethod, m2: CppMethod)", "module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {}", "it seems like CppHeaderParser is not thread safe... if skip_macros", "a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_ in main_classes:", "p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties", "module_enums = {}, {}, {}, {} for module, header_name, path", "in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate =", "p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"] for p", "generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader", "instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module, header, path", "module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes =", "methods if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods", "= [p for p in class_[\"properties\"][\"public\"] if not \"using\" in", "filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool: fields =", "filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for", "in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_:", "without a name properties = [p for p in properties", "base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class =", "join(base, f) if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path,", "= ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties: if", "p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] ==", "not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time() -", "skip_macros = [] skip_modules = [] if not windows: skip_macros", "in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] =", "any((\"<%s>\" % type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if", "module)] filtered_main_classes = [] for class_ in main_classes: specialized_template =", "= False if keep: filtered.append(f) return filtered def get_variables(header): variables", "class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions =", "platform.system() == \"Windows\" skip_macros = [] skip_modules = [] if", "if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function", "f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers", "enums def read_header(header_path, skip_macros=None): # I tried to do this", "= [e for e in header.enums if e.get(\"name\")] # skip", "ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in", "def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split()", "methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private in", "a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces =", "safe... if skip_macros is None: skip_macros = [] header_file_str =", "for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes):", "count.items(): if count >= 2: needs.append(name) needs_overloading[module] = needs return", "= [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers =", "for class_ in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]:", "1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue", "if v != text: print(\"File is different: %s\" % os.path.split(path)[1])", "load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_):", "like CppHeaderParser is not thread safe... if skip_macros is None:", "= [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f]", "from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils", "generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods):", "= platform.system() == \"Windows\" skip_macros = [] skip_modules = []", "class_ in main_classes.items(): classes_by_module[module] += class_ for module, classes in", "module, classes in classes_by_module.items(): needs = [] for class_ in", "dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types)", "in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break", "split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from", "defaultdict, OrderedDict from os.path import join from typing import List,", "namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class =", "not to_skip: message = \"Warning: Template class specialization not implemented", "header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes =", "same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"])", "in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private)", "if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE,", "header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access", "\"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m in methods:", "in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for class_", "filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool:", "and same_parameters(p1, p2): break else: return False return len(m1[\"parameters\"]) ==", "os.walk(PATH_MODULES): for f in files: path = join(base, f) if", "base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]:", "skip_macros is None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros)", "'using' != v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return", "def filter_methods_to_skip(methods): filtered_methods = [] for m in methods: if", "something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated", "from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def", "#skip_modules = [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type", "(class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else:", "generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import Instantiations from", "header.enums if e.get(\"name\")] # skip nameless enums enums = sorted(enums,", "filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties,", "headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]:", "for module, header_name, path in headers_to_generate: if (module, header_name) in", "delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return:", "namespace in namespaces: if not namespace == \"pcl\": a(\"using namespace", "m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return False", "in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions", "get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return", "v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I tried", "SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template class specialization", "index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based", "namespace) a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods", "namespace %s;\" % namespace) a(\"\\n\") for class_ in main_classes: methods", "in count.items(): if count >= 2: needs.append(name) needs_overloading[module] = needs", "seems like CppHeaderParser is not thread safe... if skip_macros is", "for methods in class_[\"methods\"].values() for m in methods) for name,", "path, keep_if_no_instantiation=False) return generated_headers def main(): import time t =", "implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp", "path, text in files_to_write.items(): if path not in written: open(path,", "{} classes_by_module = defaultdict(list) for (module, _), class_ in main_classes.items():", "class_ for module, classes in classes_by_module.items(): needs = [] for", "CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]: return", "= generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\"", "= sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module,", "from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from", "CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return", "from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP,", "in param[\"type\"]: keep = False if keep: filtered.append(f) return filtered", "the class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c", "header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)],", "skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time()", "tried to do this in multiple threads but it seems", "for m in methods) for name, count in count.items(): if", "is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \"", "import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD,", "sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header): enums =", "return filtered_methods def same_parameters(p1: Dict, p2: Dict) -> bool: fields", "m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside", "text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict()", "% module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write,", "header_name, class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading)", "class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p", "in %s\" print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"])", "access for m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree,", "found_modules.append([f, join(relative_base, f)]) return found_modules if modules is None: modules", "set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write", "and 'using' != v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"])", "v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables, key=lambda v:", "generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)]", "path = path[path.rfind(\":\") + 1:] if not any(path in type_", "f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate +=", "for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class and", "if path else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros)", "c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type)", "main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions =", "if text: output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path]", "+ class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for", "False # bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void", "m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path,", "specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip", "main_classes.items(): classes_by_module[module] += class_ for module, classes in classes_by_module.items(): needs", "\"private protected public\".split() return set([m[\"name\"] for a in access for", "base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods:", "m1[\"name\"] != m2[\"name\"]: return False # bug in CppHeaderParser #", "ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def", "for module, header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module,", "in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if", "in fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if", "in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p", "= Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in methods)", "generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations import", "= text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\")", "= False else: # check if any pure virtual method", "= unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k in", "return False def write_if_different(files_to_write, delete_others): written = [] for base,", "from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import common_includes,", "for base, folder, files in os.walk(PATH_MODULES): for f in files:", "write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module for module, _ in", "def read_header(header_path, skip_macros=None): # I tried to do this in", "v = open(path).read() if v != text: print(\"File is different:", "count >= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading def", "or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers", "= single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m) return", "OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {}, {}, {},", "files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules", "classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules):", "= [] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in", "import join from typing import List, Dict, Set from CppHeaderParser", "private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties", "for (module, header_name), text in generated_headers.items(): if text: output_path =", "get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c for module,", "c: c[\"name\"]) return filtered_main_classes def get_functions(header, module): functions = [f", "get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions", "List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private in private_methods:", "skip_modules=None): def listmod(module): found_modules = [] for base, folders, files", "= sorted(variables, key=lambda v: v[\"name\"]) return variables def get_enums(header): enums", "header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)]", "header_name, path in listmod(module)] base_headers = [(\"\", f, f) for", "ClassDefinition from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from", "print(\"File is different: %s\" % os.path.split(path)[1]) return True # print(\"File", "= {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for c", "in os.walk(PATH_MODULES): for f in files: path = join(base, f)", "[] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name,", "return filtered_main_classes def get_functions(header, module): functions = [f for f", "= needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules", "enums = [e for e in header.enums if e.get(\"name\")] #", "\"pcl::\" + module)] filtered_main_classes = [] for class_ in main_classes:", "if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private", "classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for", "continue if \"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1", "not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can", "hpp files_to_write = {} for (module, header_name), text in generated_headers.items():", "= [c for c in header.classes.values() if c[\"namespace\"] in (\"pcl\",", "read_header_file def filter_methods_for_parser_errors(methods): return [m for m in methods if", "for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) ->", "p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties =", "in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not \"union\"", "True if f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]:", "c in classes} for module, header_name in main_classes: for class_", "make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m in methods", "type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False", "same_parameters(p1: Dict, p2: Dict) -> bool: fields = [\"constant\", \"name\",", "def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES)", "filtered def get_variables(header): variables = [v for v in header.variables", "get_variables(header): variables = [v for v in header.variables if v.get(\"defaultValue\")", "for c in main_classes]) for namespace in namespaces: if not", "in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated =", "module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v =", "if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties", "os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not in modules", "join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text # loaders", "main_classes: specialized_template = class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template:", "parser = CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\")", "os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for", "t = time.time() windows = platform.system() == \"Windows\" skip_macros =", "dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) #", "in functions: keep = True if f.get(\"returns_const\"): keep = False", "modules = [m for m in modules if m not", "in classes} for module, header_name in main_classes: for class_ in", "variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]: constructors", "all(p1[f] == p2[f] for f in fields) def same_methods(m1: CppMethod,", "= dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"]))", "List[CppMethod]): filtered = [] for f in functions: keep =", "List, Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import", "if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" %", "else: classes_point_types[k] = v return classes_point_types def make_module_dirs(modules): for module", "= time.time() windows = platform.system() == \"Windows\" skip_macros = []", "\"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f] == p2[f] for f", "check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for (module, _),", "in to_ignore: continue filtered_properties.append(p) properties = filtered_properties return properties def", "if not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict,", "needs_overloading) if not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_,", "if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return", "namespaces: if not namespace == \"pcl\": a(\"using namespace %s;\" %", "os.path import join from typing import List, Dict, Set from", "c in main_classes]) for namespace in namespaces: if not namespace", "multiple threads but it seems like CppHeaderParser is not thread", "return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if", "not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type)", "= get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"]", "and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules =", "make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m", "for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" %", "modules is None: modules = MODULES_TO_BUILD if skip_modules is not", "path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else", "class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_) in class_[\"name\"]", "= main_classes_by_name_namespace.get(base_name_nsp) if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if", "typing import List, Dict, Set from CppHeaderParser import CppHeaderParser from", "methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] +", "[e for e in header.enums if e.get(\"name\")] # skip nameless", "headers_to_generate_temp = [] for module, header_name, path in headers_to_generate: if", "for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return", "from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class", "methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break return private_defined_outside def generate_class_definitions(main_classes,", "filter_class_properties(module, header, class_name, properties): key = (module, header, class_name) #", "on inheritance for module, header in main_classes: main_classes[(module, header)] =", "OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module, header)] =", "[] for class_ in classes: count = Counter(m[\"name\"] for methods", "def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) ->", "= join(base, f) if path in files_to_write: if is_file_different(path, files_to_write[path]):", "classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated", "m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not any(path in", "# check if any pure virtual method is not implemented", "header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path", "a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key", "all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in", "MODULES_TO_BUILD if skip_modules is not None: modules = [m for", "= filtered_properties return properties def get_main_classes(header, module, header_name): # header", "header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type)", "s\" % (time.time() - t,)) if __name__ == '__main__': main()", "headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path]))", "in multiple threads but it seems like CppHeaderParser is not", "m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f", "a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key =", "if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules is", "if any pure virtual method is not implemented all_implemented_inherited_methods =", "= [] for m_private in private_methods: for m_outside in methods_declared_outside:", "-> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums", "\"\"\" main_classes, module_functions, module_variables, module_enums = {}, {}, {}, {}", "for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\"", "return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside:", "+= class_ for module, classes in classes_by_module.items(): needs = []", "module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module,", "e in header.enums if e.get(\"name\")] # skip nameless enums enums", "os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base,", "[] for base, folder, files in os.walk(PATH_MODULES): for f in", "= join(PCL_BASE, path) if path else join(PCL_BASE, module, header_name) header", "generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import", "classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m", "= class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected =", "if class_[\"abstract\"]: can_be_instantiated = False else: # check if any", "False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type)", "base, folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m", "HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function", "break return private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str],", "= \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers,", "2 text = [] if something_instantiated or keep_if_no_instantiation: text =", "header_name, path) for module in modules for header_name, path in", "methods += private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in", "files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" +", "\\ generate_main_loader, make_namespace_class, read_header_file def filter_methods_for_parser_errors(methods): return [m for m", "header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path,", "a in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def", "[] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers", "class can be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for", "if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods =", "[] for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP:", "generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules)", "module_variables, module_enums = {}, {}, {}, {} for module, header_name,", "written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder", "instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = [] if", "loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module,", "False for param in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if", "for m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue", "join from typing import List, Dict, Set from CppHeaderParser import", "SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files:", "= len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if", "private_methods: for m_outside in methods_declared_outside: if same_methods(m_private, m_outside): private_defined_outside.append(m_private) break", "time t = time.time() windows = platform.system() == \"Windows\" skip_macros", "= main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module,", "header_name)] = get_enums(header) classes = [c for module, header, path", "print(\"generated in %.2f s\" % (time.time() - t,)) if __name__", "path) # write new files for path, text in files_to_write.items():", "= read_headers(base_path, header_name, module) main_classes = [c for c in", "headers_to_generate += base_headers headers_to_generate_temp = [] for module, header_name, path", "class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda", "for a in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]])", "[] if something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function]", "# I tried to do this in multiple threads but", "\\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import", "in class_[\"name\"] if specialized_template: to_skip = any((\"<%s>\" % type_) in", "return filtered def get_variables(header): variables = [v for v in", "generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import generate_loader", "name, count in count.items(): if count >= 2: needs.append(name) needs_overloading[module]", "{}, {}, {} for module, header_name, path in headers_to_generate[:]: header_full_path", "header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES):", "make_module_dirs(modules) # hpp files_to_write = {} for (module, header_name), text", "header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions))", "in methods) for name, count in count.items(): if count >=", "[] for class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\"", "if not class_[\"can_be_instantiated\"]: constructors = [] class_def = ClassDefinition(class_, constructors,", "= [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv", "p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties", "in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message = \"Warning: Template class", "common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP,", "# bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\"", "class_[\"name\"], class_properties) constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if", "\"pcl::%s\" % module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda", "protected public\".split() return set([m[\"name\"] for a in access for m", "{} for module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE,", "for (module, _), class_ in main_classes.items(): classes_by_module[module] += class_ for", "methods in class_[\"methods\"].values() for m in methods) for name, count", "if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return", "bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is", "k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types", "os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules = set(module", "class_name, properties): key = (module, header, class_name) # ignore properties", "% (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass", "(module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp", "in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties = [p", "return generated_headers def main(): import time t = time.time() windows", "\"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered", "if skip_modules is not None: modules = [m for m", "# write new files for path, text in files_to_write.items(): if", "Template class specialization not implemented for class %s in %s\"", "base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def", "listmod(module)] base_headers = [(\"\", f, f) for f in os.listdir(PCL_BASE)", "header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated = False else:", "to_skip = any((\"<%s>\" % type_) in class_[\"name\"] for type_ in", "found_modules if modules is None: modules = MODULES_TO_BUILD if skip_modules", "in modules for header_name, path in listmod(module)] base_headers = [(\"\",", "= get_headers(skip_modules=skip_modules) not_every_point_type = \"--not-every-point-type\" in sys.argv generated_headers = generate(all_headers,", "{} for (module, header_name), text in generated_headers.items(): if text: output_path", "bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return all(p1[f]", "= OrderedDict() for module, header, path in headers_to_generate: generated_headers[(module, header)]", "# ignore properties without a name properties = [p for", "for module in modules for header_name, path in listmod(module)] base_headers", "class_ in main_classes[(module, header_name)]: can_be_instantiated = True if class_[\"abstract\"]: can_be_instantiated", "module, header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header,", "implemented for class %s in %s\" print(message % (class_[\"name\"], header_name))", "classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return", "Set[str]: access = \"private protected public\".split() return set([m[\"name\"] for a", "is_file_different(path, text): v = open(path).read() if v != text: print(\"File", "return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private", "if text: loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items():", "module_functions, module_variables, module_enums = {}, {}, {}, {} for module,", "variables def get_enums(header): enums = [e for e in header.enums", "CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE,", "f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules if modules is None:", "header_name), text in generated_headers.items(): if text: output_path = join(PATH_MODULES, module,", "HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass)", "= set([c[\"namespace\"] for c in main_classes]) for namespace in namespaces:", "for class_ in classes: count = Counter(m[\"name\"] for methods in", "read_headers(base_path, header_name, module) main_classes = [c for c in header.classes.values()", "ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import", "Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"]", "in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types:", "MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP", "!= v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return variables", "\"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)])", "header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes,", "for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1,", "-> str: text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module,", "generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader,", "from generators.instantiations import Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils", "f in files: path = join(base, f) if path in", "module): functions = [f for f in header.functions if f[\"namespace\"]", "[c for module, header, path in headers_to_generate for c in", "[m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for p1 in", "(\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)] functions =", "not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for", "constructors, variables, others = split_methods_by_type(methods, class_properties, needs_overloading) if not class_[\"can_be_instantiated\"]:", "key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions:", "folders, files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in", "CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config import", "classes in main_classes.values() for c in classes} for module, header_name", "class_name) # ignore properties without a name properties = [p", "+ path) # write new files for path, text in", "EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from generators.definitions.method", "main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated = True if", "write new files for path, text in files_to_write.items(): if path", "module, header_name in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated", "for e in header.enums if e.get(\"name\")] # skip nameless enums", "get_enums(header): enums = [e for e in header.enums if e.get(\"name\")]", "try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes):", "class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access =", "not in skip_modules] headers_to_generate = [(module, header_name, path) for module", "in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES):", "= [f for f in header.functions if f[\"namespace\"] in (\"pcl\",", "= \"private protected public\".split() return set([m[\"name\"] for a in access", "path)) a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes]) for", "def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for (module,", "keep = True if f.get(\"returns_const\"): keep = False for param", "class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"]", "\"\\n\".join(text) generated_headers = OrderedDict() for module, header, path in headers_to_generate:", "path_loader = join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers)", "clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def", "header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name)", "path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes =", "functions = [f for f in header.functions if f[\"namespace\"] in", "in headers_to_generate[:]: header_full_path = join(PCL_BASE, path) if path else join(PCL_BASE,", "for c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" +", "f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = [] for module, header_name,", "for f in fields) def same_methods(m1: CppMethod, m2: CppMethod) ->", "f) if f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True)", "os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list)", "[\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules)", "= get_enums(header) classes = [c for module, header, path in", "output_path = join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text", "CppHeaderParser parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return header", "join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] =", "v in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables", "module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base =", "[] for m_private in private_methods: for m_outside in methods_declared_outside: if", "p in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties", "path in headers_to_generate for c in main_classes[(module, header)]] dependency_tree =", "p2: Dict) -> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\",", "files_to_write[output_path] = text # loaders loader_modules = defaultdict(list) for (module,", "None: modules = [m for m in modules if m", "in access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_:", "from collections import defaultdict, OrderedDict from os.path import join from", "not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict,", "= sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes def get_functions(header, module):", "p2): break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def", "= join(PATH_MODULES, \"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER]", "listmod(module): found_modules = [] for base, folders, files in os.walk(join(PCL_BASE,", "main(): import time t = time.time() windows = platform.system() ==", "= check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) ->", "methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation)", "in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module, header_name,", "dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods)", "loader_modules = defaultdict(list) for (module, header_name), text in generated_headers.items(): if", "open(path).read() if v != text: print(\"File is different: %s\" %", "[c for c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\"", "+ \"pp\") files_to_write[output_path] = text # loaders loader_modules = defaultdict(list)", "key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for", "_ in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for", "import time t = time.time() windows = platform.system() == \"Windows\"", "filtered_properties return properties def get_main_classes(header, module, header_name): # header =", "[] for f in functions: keep = True if f.get(\"returns_const\"):", "base_headers = [(\"\", f, f) for f in os.listdir(PCL_BASE) if", "generated_headers def main(): import time t = time.time() windows =", "if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated", "do this in multiple threads but it seems like CppHeaderParser", "= get_methods_defined_outside(header_functions) class_definitions = generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside)", "List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for m_private", "class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not \"union\" in", "in class_[\"methods\"].values() for m in methods) for name, count in", "key=lambda v: v[\"name\"]) return variables def get_enums(header): enums = [e", "header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c", "skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser", "defaultdict(list) for (module, header_name), text in generated_headers.items(): if text: loader_modules[module", "any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False", "sys from collections import Counter from collections import defaultdict, OrderedDict", "delete_others: os.remove(path) print(\"Deleted: \" + path) # write new files", "for module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)],", "\" + path) # write new files for path, text", "[] skip_modules = [] if not windows: skip_macros = [\"_MSC_VER\"]", "m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if not any(path", "if base_class and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods -", "any(base.endswith(m) for m in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:]", "from generators.definitions.submodule_loader import generate_loader from generators.definitions.templated_class import ClassDefinition from generators.instantiations", "get_functions(header, module): functions = [f for f in header.functions if", "if keep: filtered.append(f) return filtered def get_variables(header): variables = [v", "unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k in classes_point_types:", "module in modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir):", "union_properties = [p for nested_class in class_[\"nested_classes\"] for p in", "f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" %", "[f for f in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\",", "files in os.walk(join(PCL_BASE, module)): if any(base.endswith(m) for m in SUBMODULES_TO_SKIP):", "CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES,", "sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header,", "os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written = [] for", "access for m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass)", "= read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module,", "os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if v", "m in methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if", "in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties", "def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f in functions:", "in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v return classes_point_types def", "+= private_methods_defined_outside(private_and_protected, methods_defined_outside) class_properties = [p for p in class_[\"properties\"][\"public\"]", "(module, header, class_name) # ignore properties without a name properties", "if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]:", "in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"]", "sys.argv generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in", "c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for", "header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module, header)] header_classes", "if e.get(\"name\")] # skip nameless enums enums = sorted(enums, key=lambda", "generated_headers = generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f", "header, path in headers_to_generate for c in main_classes[(module, header)]] dependency_tree", "return type path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") +", "new files for path, text in files_to_write.items(): if path not", "return set([m[\"name\"] for a in access for m in class_[\"methods\"][a]", "shutil import sys from collections import Counter from collections import", "len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]:", "for p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and", "sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): #", "f) if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path])", "instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)],", "%s;\" % namespace) a(\"\\n\") for class_ in main_classes: methods =", "is None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser", "= generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header,", "% module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f:", "skip_modules] headers_to_generate = [(module, header_name, path) for module in modules", "parser.debug = False header = parser.CppHeader(header_file_str, argType=\"string\") return header def", "f)]) return found_modules if modules is None: modules = MODULES_TO_BUILD", "path in headers_to_generate: if (module, header_name) in HEADERS_TO_SKIP: continue headers_to_generate_temp.append(tuple([module,", "module, \"pcl::%s::\" % module)] functions = sorted(functions, key=lambda f: f[\"name\"])", "in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp = []", "module, header_name): # header = read_headers(base_path, header_name, module) main_classes =", "_), class_ in main_classes.items(): classes_by_module[module] += class_ for module, classes", "= MODULES_TO_BUILD if skip_modules is not None: modules = [m", "f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]):", "m2[\"name\"]: return False # bug in CppHeaderParser # in \"void", "generate(all_headers, skip_macros, not_every_point_type) write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" %", "the same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others):", "inside modules based on inheritance for module, header in main_classes:", "for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate += base_headers headers_to_generate_temp", "return enums def read_header(header_path, skip_macros=None): # I tried to do", "in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others:", "filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected, methods_defined_outside)", "properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key]", "name properties = [p for p in properties if p[\"name\"]]", "same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"] != m2[\"name\"]:", "= instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text = []", "modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True): modules", "write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) ->", "properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p) properties = filtered_properties", "a(\"\") namespaces = set([c[\"namespace\"] for c in main_classes]) for namespace", "others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name,", "in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods =", "in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated = True", "Counter from collections import defaultdict, OrderedDict from os.path import join", "= [] for module, header_name, path in headers_to_generate: if (module,", "methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected", "windows = platform.system() == \"Windows\" skip_macros = [] skip_modules =", "PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP,", "-> List[CppMethod]: private_defined_outside = [] for m_private in private_methods: for", "= [] skip_modules = [] if not windows: skip_macros =", "in p[\"type\"]] union_properties = [p for nested_class in class_[\"nested_classes\"] for", "break else: return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods:", "not windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules =", "\"Callback\" in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function =", "in header.functions if f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module,", "main_classes): \"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace =", "\"using\" in p[\"type\"] and not \"union\" in p[\"type\"]] union_properties =", "header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes,", "def listmod(module): found_modules = [] for base, folders, files in", "if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\"", "for k, v in extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v)", "class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return", "filtered.append(f) return filtered def get_variables(header): variables = [v for v", "= [] for class_ in main_classes: specialized_template = class_.get(\"template\") and", "delete_others): written = [] for base, folder, files in os.walk(PATH_MODULES):", "== p2[f] for f in fields) def same_methods(m1: CppMethod, m2:", "if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted:", "- all_implemented_inherited_methods: can_be_instantiated = False class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type):", "filtered_main_classes = [] for class_ in main_classes: specialized_template = class_.get(\"template\")", "return True # print(\"File is the same: %s\" % os.path.split(path)[1])", "return found_modules if modules is None: modules = MODULES_TO_BUILD if", "in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]: keep = False if", "os.remove(path) print(\"Deleted: \" + path) # write new files for", "classes = [c for module, header, path in headers_to_generate for", "set([c[\"namespace\"] for c in main_classes]) for namespace in namespaces: if", "= [] for class_ in classes: count = Counter(m[\"name\"] for", "% os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written = []", "(m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument", "for path, text in files_to_write.items(): if path not in written:", "= [m for m in modules if m not in", "type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same", "module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header,", "= path[path.rfind(\":\") + 1:] if not any(path in type_ for", "\"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {},", "= filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = []", "-> bool: fields = [\"constant\", \"name\", \"raw_type\", \"reference\", \"static\"] return", "check if any pure virtual method is not implemented all_implemented_inherited_methods", "module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod]) -> str: text", "\"Warning: Template class specialization not implemented for class %s in", "not boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2:", "if key in ATTRIBUTES_TO_SKIP: to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = []", "in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module, headers", "in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for p1", "header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate", "make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if", "join(relative_base, f)]) return found_modules if modules is None: modules =", "in modules if m not in skip_modules] headers_to_generate = [(module,", "in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False #", "to do this in multiple threads but it seems like", "header_name), text in generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for", "class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message =", "filtered_properties.append(p) properties = filtered_properties return properties def get_main_classes(header, module, header_name):", "\"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path =", "in listmod(module)] base_headers = [(\"\", f, f) for f in", "classes_point_types def make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES,", "len(m[\"parameters\"]) == 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not", "\"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path) #", "class_properties += union_properties class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors,", "read_header(header_full_path, skip_macros) main_classes[(module, header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)]", "for m_private in private_methods: for m_outside in methods_declared_outside: if same_methods(m_private,", "needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None): def", "module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties):", "import generate_function_definitions, get_methods_defined_outside from generators.definitions.method import split_methods_by_type from generators.definitions.submodule_loader import", "for p in properties if p[\"name\"]] if key in ATTRIBUTES_TO_SKIP:", "for module, header_name in main_classes: for class_ in main_classes[(module, header_name)]:", "in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]]", "filtered = [] for f in functions: keep = True", "else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module, header_name)]", ":return: OrderedDict \"\"\" main_classes, module_functions, module_variables, module_enums = {}, {},", "a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for c in", "= [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module,", "for f in files: path = join(base, f) if path", "get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if", "to_ignore = ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties:", "modules based on inheritance for module, header in main_classes: main_classes[(module,", "main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros)", "header, class_name) # ignore properties without a name properties =", "header = read_headers(base_path, header_name, module) main_classes = [c for c", "= [] for f in functions: keep = True if", "import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from generators.config", "for p in nested_class[\"properties\"][\"public\"] if \"union\" in nested_class[\"name\"]] class_properties +=", "if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module =", "\"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader = join(PATH_MODULES, \"_%s_loader.cpp\"", "function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for module, header,", "boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function: continue filtered_methods.append(m)", "is different: %s\" % os.path.split(path)[1]) return True # print(\"File is", "not namespace == \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\")", "\\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from", "m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for", "modules: module_dir = join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def", "= [] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug", "in (\"void\", \"bool\")] def filter_methods_to_skip(methods): filtered_methods = [] for m", "get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"], class_[\"name\"]) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class", "import CppMethod import generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER,", "= [(\"\", f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")]", "pass if os.path.exists(PATH_MODULES): shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module", "# print(\"File is the same: %s\" % os.path.split(path)[1]) return False", "generated_headers.items(): if text: loader_modules[module or \"base\"].append(header_name) for module, headers in", "functions: keep = True if f.get(\"returns_const\"): keep = False for", "m in class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine", "not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes, module_functions, module_variables,", "def is_file_different(path, text): v = open(path).read() if v != text:", "header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)] = get_variables(header)", "module, header in main_classes: main_classes[(module, header)] = list(sorted(main_classes[(module, header)], key=index_for_class))", "= generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros,", "if f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]: for", "= (module, header, class_name) # ignore properties without a name", "is None: modules = MODULES_TO_BUILD if skip_modules is not None:", "header_name + \"pp\") files_to_write[output_path] = text # loaders loader_modules =", "Dict, Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod", "header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables,", "flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be instantiated\"\"\" main_classes_by_name_namespace", "p2 in m2[\"parameters\"]: if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2):", "Set from CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import", "a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path))", "CppHeaderParser import CppHeaderParser from CppHeaderParser.CppHeaderParser import CppMethod import generators.dependency_tree from", "in header.variables if v.get(\"defaultValue\") and 'using' != v.get('type')] variables =", "windows: skip_macros = [\"_MSC_VER\"] #skip_modules = [\"visualization\"] skip_modules = []", "class_ in classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values()", "in generated_headers.keys()) make_module_dirs(modules) # hpp files_to_write = {} for (module,", "m in class_[\"methods\"][a] if m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]:", "class_properties = filter_class_properties(module, header_name, class_[\"name\"], class_properties) constructors, variables, others =", "Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function", "properties): key = (module, header, class_name) # ignore properties without", "== 1 boost_function = single_argument and m[\"parameters\"][0][\"type\"].startswith(\"boost::function\") if not boost_function:", "= join(PATH_MODULES, f) if f not in modules and os.path.isdir(folder):", "key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None): # I", "CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split() return set([m[\"name\"]", "v.get('type')] variables = sorted(variables, key=lambda v: v[\"name\"]) return variables def", "methods_defined_outside: List[CppMethod]) -> str: text = [] a = text.append", "os import platform import shutil import sys from collections import", "= [] for base, folders, files in os.walk(join(PCL_BASE, module)): if", "text # loaders loader_modules = defaultdict(list) for (module, header_name), text", "os.path.split(path)[1]) return True # print(\"File is the same: %s\" %", "list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside", "files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate,", "return \"\\n\".join(text) def filter_class_properties(module, header, class_name, properties): key = (module,", "count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for m in", "but it seems like CppHeaderParser is not thread safe... if", "= len(instantiation_function.split(\"\\n\")) > 2 text = [] if something_instantiated or", "classes_by_module[module] += class_ for module, classes in classes_by_module.items(): needs =", "{make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for c in", "threads but it seems like CppHeaderParser is not thread safe...", "keep: filtered.append(f) return filtered def get_variables(header): variables = [v for", "return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) ->", "+ 1:] if not any(path in type_ for type_ in", "f in files: if f.endswith(\".h\"): found_modules.append([f, join(relative_base, f)]) return found_modules", "module) main_classes = [c for c in header.classes.values() if c[\"namespace\"]", "function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module,", "all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class", "= [c for module, header, path in headers_to_generate for c", "= sorted(enums, key=lambda v: v[\"name\"]) return enums def read_header(header_path, skip_macros=None):", "private_defined_outside def generate_class_definitions(main_classes, module, header_name, path, needs_overloading: List[str], methods_defined_outside: List[CppMethod])", "= class_.get(\"template\") and \"<\" in class_[\"name\"] if specialized_template: to_skip =", "in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the", "in SUBMODULES_TO_SKIP): continue relative_base = os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in", "# skip nameless enums enums = sorted(enums, key=lambda v: v[\"name\"])", "for p1 in m1[\"parameters\"]: for p2 in m2[\"parameters\"]: if m1[\"name\"]", "= join(PATH_MODULES, module, header_name + \"pp\") files_to_write[output_path] = text #", "not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module,", "in methods if not m[\"name\"] in (\"void\", \"bool\")] def filter_methods_to_skip(methods):", "m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in m[\"name\"]: single_argument =", "path = join(base, f) if path in files_to_write: if is_file_different(path,", "module_enums[(module, header_name)] = get_enums(header) classes = [c for module, header,", "SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside from", "found_modules = [] for base, folders, files in os.walk(join(PCL_BASE, module)):", "= [\"visualization\"] skip_modules = [] all_headers = get_headers(skip_modules=skip_modules) not_every_point_type =", "def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules", "else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"]) return filtered_main_classes", "= set(module for module, _ in generated_headers.keys()) make_module_dirs(modules) # hpp", "private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = [] for", "not \"union\" in p[\"type\"]] union_properties = [p for nested_class in", ">= 2: needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None,", "argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except FileNotFoundError: pass", "header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False", "% os.path.split(path)[1]) return True # print(\"File is the same: %s\"", "1:] if not any(path in type_ for type_ in [m1[\"rtnType\"],", "needs = [] for class_ in classes: count = Counter(m[\"name\"]", "f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f not", "v: v[\"name\"]) return variables def get_enums(header): enums = [e for", "= generators.dependency_tree.DependencyTree(classes) loaded_point_types = load_yaml_point_types(not_every_point_type) classes_point_types: OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first", "header, path in headers_to_generate: generated_headers[(module, header)] = generate_header(module, header, path,", "files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path)", "for name, count in count.items(): if count >= 2: needs.append(name)", ") instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text", "different: %s\" % os.path.split(path)[1]) return True # print(\"File is the", "= filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"] methods += private_methods_defined_outside(private_and_protected,", "= get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class = main_classes_by_name_namespace.get(base_name_nsp)", "False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod])", "f[\"namespace\"] in (\"pcl\", \"pcl::\", \"pcl::%s\" % module, \"pcl::%s::\" % module)]", "[] header_file_str = read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug =", "2: needs.append(name) needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None):", "from typing import List, Dict, Set from CppHeaderParser import CppHeaderParser", "for f in functions: keep = True if f.get(\"returns_const\"): keep", "class_[\"methods\"].values() for m in methods) for name, count in count.items():", "properties without a name properties = [p for p in", "generators.dependency_tree from generators.config import common_includes, PCL_BASE, PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\", "= get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module,", "load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k,", "p in class_[\"properties\"][\"public\"] if not \"using\" in p[\"type\"] and not", "from collections import Counter from collections import defaultdict, OrderedDict from", "filter_methods_to_skip(methods): filtered_methods = [] for m in methods: if (m[\"parent\"][\"name\"],", "for header_name, path in listmod(module)] base_headers = [(\"\", f, f)", "CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c: c[\"name\"])", "= get_variables(header) module_enums[(module, header_name)] = get_enums(header) classes = [c for", "if \"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module,", "m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class can be", "class_[\"can_be_instantiated\"] = can_be_instantiated def load_yaml_point_types(not_every_point_type): classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types", "loader_modules[module or \"base\"].append(header_name) for module, headers in loader_modules.items(): path_loader =", "classes inside modules based on inheritance for module, header in", "and base_class[\"abstract\"]: base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated", "= [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text) generated_headers = OrderedDict() for", "class_[\"methods\"][a] if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the", "nameless enums enums = sorted(enums, key=lambda v: v[\"name\"]) return enums", "def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected public\".split()", "PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\", "main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in main_classes.values() for", "== m2[\"name\"] and same_parameters(p1, p2): break else: return False return", "[(\"\", f, f) for f in os.listdir(PCL_BASE) if f.endswith(\".h\")] headers_to_generate", "shutil.rmtree(PATH_MODULES) def check_if_needs_overloading(main_classes): needs_overloading = {} classes_by_module = defaultdict(list) for", "\"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES,", "path = m1.get(\"path\", m2.get(\"path\")) path = path[path.rfind(\":\") + 1:] if", "a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods =", "# loaders loader_modules = defaultdict(list) for (module, header_name), text in", "modules = MODULES_TO_BUILD if skip_modules is not None: modules =", "= os.path.abspath(base).replace(PCL_BASE, \"\")[1:] for f in files: if f.endswith(\".h\"): found_modules.append([f,", "= get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] =", "check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def generate_header(module, header, path, keep_if_no_instantiation) -> str:", "path) for module in modules for header_name, path in listmod(module)]", "\"_%s_loader.cpp\" % module) files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules)", "header_name)] = get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module)", "for module, header_name, path in headers_to_generate[:]: header_full_path = join(PCL_BASE, path)", "if f not in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def", "get_functions(header, module) module_variables[(module, header_name)] = get_variables(header) module_enums[(module, header_name)] = get_enums(header)", "virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class =", "methods: if (m[\"parent\"][\"name\"], m[\"name\"]) in METHODS_TO_SKIP: continue if \"Callback\" in", "(\"pcl\", \"pcl::\" + module)] filtered_main_classes = [] for class_ in", "def get_enums(header): enums = [e for e in header.enums if", "continue headers_to_generate_temp.append(tuple([module, header_name, path])) return headers_to_generate_temp def get_pure_virtual_methods(class_: CppHeaderParser.CppClass) ->", "pure virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class", "return all(p1[f] == p2[f] for f in fields) def same_methods(m1:", "make_module_dirs(modules): for module in modules: module_dir = join(PATH_MODULES, module) if", "if not m[\"pure_virtual\"]]) def flag_instantiatable_class(dependency_tree, main_classes): \"\"\"determine if the class", "= True if class_[\"abstract\"]: can_be_instantiated = False else: # check", "fields) def same_methods(m1: CppMethod, m2: CppMethod) -> bool: if m1[\"name\"]", "module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions)", "for module in modules: module_dir = join(PATH_MODULES, module) if not", "needs_overloading[module] = needs return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module):", "if modules is None: modules = MODULES_TO_BUILD if skip_modules is", "base_pure_virtual_methods = get_pure_virtual_methods(base_class) if base_pure_virtual_methods - all_implemented_inherited_methods: can_be_instantiated = False", "path) if path else join(PCL_BASE, module, header_name) header = read_header(header_full_path,", "p[\"type\"] and not \"union\" in p[\"type\"]] union_properties = [p for", "[p for p in properties if p[\"name\"]] if key in", "headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree, main_classes) def", "be instantiated\"\"\" main_classes_by_name_namespace = {make_namespace_class(c[\"namespace\"], c[\"name\"]): c for classes in", "= any((\"<%s>\" % type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP)", "False # same parameters for p1 in m1[\"parameters\"]: for p2", "f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered", "if path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for", "% type_) in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not", "m[\"pure_virtual\"]]) def get_all_class_methods_not_pure_virtual(class_: CppHeaderParser.CppClass) -> Set[str]: access = \"private protected", "generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def generate(headers_to_generate, skip_macros, not_every_point_type=False)", "not any(path in type_ for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return", "properties def get_main_classes(header, module, header_name): # header = read_headers(base_path, header_name,", "return filtered def filter_module_level_functions(functions: List[CppMethod]): filtered = [] for f", "skip_modules is not None: modules = [m for m in", "c in header.classes.values() if c[\"namespace\"] in (\"pcl\", \"pcl::\" + module)]", "classes in classes_by_module.items(): needs = [] for class_ in classes:", "% module)] functions = sorted(functions, key=lambda f: f[\"name\"]) filtered =", "files in os.walk(PATH_MODULES): for f in files: path = join(base,", "in f[\"parameters\"]: for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP: if type_ in param[\"type\"]:", "def write_if_different(files_to_write, delete_others): written = [] for base, folder, files", "headers_to_generate = [(module, header_name, path) for module in modules for", "in %.2f s\" % (time.time() - t,)) if __name__ ==", "return False return len(m1[\"parameters\"]) == len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside:", "path in listmod(module)] base_headers = [(\"\", f, f) for f", "module_variables[(module, header)], module_enums[(module, header)], ) instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated =", "List[str], methods_defined_outside: List[CppMethod]) -> str: text = [] a =", "in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes = sorted(filtered_main_classes, key=lambda c:", "header_name, module) main_classes = [c for c in header.classes.values() if", "modules if m not in skip_modules] headers_to_generate = [(module, header_name,", "classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"], class_[\"name\"])) # sort classes inside modules based on inheritance", "[] class_def = ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\")", "== \"pcl\": a(\"using namespace %s;\" % namespace) a(\"\\n\") for class_", "for classes in main_classes.values() for c in classes} for module,", "boost_function: continue filtered_methods.append(m) return filtered_methods def same_parameters(p1: Dict, p2: Dict)", "c[\"name\"]): c for classes in main_classes.values() for c in classes}", "text): v = open(path).read() if v != text: print(\"File is", "%s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written =", "# same parameters for p1 in m1[\"parameters\"]: for p2 in", "= generate_class_definitions(header_classes, module, header, path, methods_need_overloading.get(module), methods_defined_outside) function_definitions = generate_function_definitions(header_functions,", "for class %s in %s\" print(message % (class_[\"name\"], header_name)) elif", "in generated_headers.items(): if text: output_path = join(PATH_MODULES, module, header_name +", "= ClassDefinition(class_, constructors, variables, others, module) a(class_def.to_class_function_definition()) a(\"\") return \"\\n\".join(text)", "import Counter from collections import defaultdict, OrderedDict from os.path import", "OrderedDict = dependency_tree.get_point_types_with_dependencies(loaded_point_types) classes_sorted_base_first = list(dependency_tree.leaf_iterator()) def index_for_class(class_): return classes_sorted_base_first.index(make_namespace_class(class_[\"namespace\"],", "for f in os.listdir(PATH_MODULES): folder = join(PATH_MODULES, f) if f", "in modules and os.path.isdir(folder): shutil.rmtree(folder, ignore_errors=True) def write_stuff_if_needed(generated_headers: OrderedDict, delete_others=True):", "type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters for", "main_classes = [c for c in header.classes.values() if c[\"namespace\"] in", "if path in files_to_write: if is_file_different(path, files_to_write[path]): open(path, \"w\").write(files_to_write[path]) written.append(path)", "if not \"using\" in p[\"type\"] and not \"union\" in p[\"type\"]]", "in \"void ImageGrabber<PointT>::publish\", \"void ImageGrabber<PointT>::\" is the return type path", "c for classes in main_classes.values() for c in classes} for", "for p in properties: if p[\"name\"] in to_ignore: continue filtered_properties.append(p)", "instantiation_function = instantiations.generate_instantiation_function(has_functions=bool(header_functions)) something_instantiated = len(instantiation_function.split(\"\\n\")) > 2 text =", "False else: # check if any pure virtual method is", "methods_defined_outside) function_definitions = generate_function_definitions(header_functions, module, header, not_every_point_type=not_every_point_type) instantiations = Instantiations(header_classes,", "same: %s\" % os.path.split(path)[1]) return False def write_if_different(files_to_write, delete_others): written", "return \"\\n\".join(text) generated_headers = OrderedDict() for module, header, path in", "if v.get(\"defaultValue\") and 'using' != v.get('type')] variables = sorted(variables, key=lambda", "files for path, text in files_to_write.items(): if path not in", "for namespace in namespaces: if not namespace == \"pcl\": a(\"using", "public\".split() return set([m[\"name\"] for a in access for m in", "get_enums(header) classes = [c for module, header, path in headers_to_generate", "header)], key=index_for_class)) headers_to_generate = sort_headers_by_dependencies(headers_to_generate, skip_macros=skip_macros) methods_need_overloading = check_if_needs_overloading(main_classes) flag_instantiatable_class(dependency_tree,", "if skip_macros is None: skip_macros = [] header_file_str = read_header_file(header_path,", "> 2 text = [] if something_instantiated or keep_if_no_instantiation: text", "a(EXPLICIT_INCLUDES.get((module, header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"]", "ATTRIBUTES_TO_SKIP[key] filtered_properties = [] for p in properties: if p[\"name\"]", "for a in access for m in class_[\"methods\"][a] if not", "= [p for nested_class in class_[\"nested_classes\"] for p in nested_class[\"properties\"][\"public\"]", "get_main_classes(header, module, header_name) module_functions[(module, header_name)] = get_functions(header, module) module_variables[(module, header_name)]", "open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f in os.listdir(PATH_MODULES): folder =", "= Instantiations(header_classes, module, header, classes_point_types, module_variables[(module, header)], module_enums[(module, header)], )", "\"static\"] return all(p1[f] == p2[f] for f in fields) def", "classes_point_types = unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v", "in m[\"name\"]: single_argument = len(m[\"parameters\"]) == 1 boost_function = single_argument", "generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\" main_classes,", "= filter_methods_for_parser_errors(methods) methods = filter_methods_to_skip(methods) private_and_protected = class_[\"methods\"][\"private\"] + class_[\"methods\"][\"protected\"]", "str: text = [] a = text.append a(common_includes) a(EXPLICIT_INCLUDES.get((module, header_name),", "print(message % (class_[\"name\"], header_name)) elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE:", "base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for base_name_nsp in dependency_tree.breadth_first_iterator(namespace_class): base_class", "if m1[\"name\"] == m2[\"name\"] and same_parameters(p1, p2): break else: return", "[m for m in modules if m not in skip_modules]", "% namespace) a(\"\\n\") for class_ in main_classes: methods = class_[\"methods\"][\"public\"]", "from os.path import join from typing import List, Dict, Set", "= [] for p in properties: if p[\"name\"] in to_ignore:", "join(PATH_MODULES, f) if f not in modules and os.path.isdir(folder): shutil.rmtree(folder,", "path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules): for f", "any pure virtual method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_)", "can_be_instantiated = False else: # check if any pure virtual", "path else join(PCL_BASE, module, header_name) header = read_header(header_full_path, skip_macros) main_classes[(module,", "f.get(\"returns_const\"): keep = False for param in f[\"parameters\"]: for type_", "in class_[\"name\"] for type_ in SPECIALIZED_TEMPLATED_TYPES_TO_SKIP) if not to_skip: message", "= parser.CppHeader(header_file_str, argType=\"string\") return header def clean(): try: os.remove(PATH_LOADER) except", "text: print(\"File is different: %s\" % os.path.split(path)[1]) return True #", "files_to_write[path_loader] = generate_loader(module, headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if", "unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items():", "False def write_if_different(files_to_write, delete_others): written = [] for base, folder,", "class_properties = [p for p in class_[\"properties\"][\"public\"] if not \"using\"", "for type_ in [m1[\"rtnType\"], m2[\"rtnType\"]]): return False # same parameters", "in classes: count = Counter(m[\"name\"] for methods in class_[\"methods\"].values() for", "\"union\" in nested_class[\"name\"]] class_properties += union_properties class_properties = filter_class_properties(module, header_name,", "# header = read_headers(base_path, header_name, module) main_classes = [c for", "join(PATH_MODULES, module) if not os.path.exists(module_dir): os.makedirs(module_dir) def is_file_different(path, text): v", "files_to_write.items(): if path not in written: open(path, \"w\").write(files_to_write[path]) def delete_other_dirs(modules):", "= read_header_file(header_path, skip_macros) parser = CppHeaderParser parser.debug = False header", "write_stuff_if_needed(generated_headers, delete_others=True) print(\"generated in %.2f s\" % (time.time() - t,))", "main_classes.values() for c in classes} for module, header_name in main_classes:", "{}, {} for module, header_name, path in headers_to_generate[:]: header_full_path =", "%.2f s\" % (time.time() - t,)) if __name__ == '__main__':", "headers_to_generate for c in main_classes[(module, header)]] dependency_tree = generators.dependency_tree.DependencyTree(classes) loaded_point_types", "folder = join(PATH_MODULES, f) if f not in modules and", "= sorted(functions, key=lambda f: f[\"name\"]) filtered = filter_module_level_functions(functions) return filtered", "elif (module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes", "base_class = main_classes_by_name_namespace.get(base_name_nsp) if base_class: base_class_methods = get_all_class_methods_not_pure_virtual(base_class) all_implemented_inherited_methods.update(base_class_methods) for", "header_name in main_classes: for class_ in main_classes[(module, header_name)]: can_be_instantiated =", "unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies, \\ generate_main_loader, make_namespace_class, read_header_file", "classes} for module, header_name in main_classes: for class_ in main_classes[(module,", "if not namespace == \"pcl\": a(\"using namespace %s;\" % namespace)", "classes_by_module = defaultdict(list) for (module, _), class_ in main_classes.items(): classes_by_module[module]", "os.makedirs(module_dir) def is_file_different(path, text): v = open(path).read() if v !=", "return needs_overloading def get_headers(modules=None, skip_modules=None): def listmod(module): found_modules = []", "class_ in main_classes: methods = class_[\"methods\"][\"public\"] methods = filter_methods_for_parser_errors(methods) methods", "extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in extra_point_types.items(): if k", "+ module)] filtered_main_classes = [] for class_ in main_classes: specialized_template", "= unpack_yaml_point_types(\"point_types_generated.yml\", not_every_point_type) extra_point_types = unpack_yaml_point_types(\"point_types_extra.yml\") for k, v in", "headers) files_to_write[PATH_LOADER] = generate_main_loader(loader_modules) write_if_different(files_to_write, delete_others) if delete_others: delete_other_dirs(modules) def", "len(m2[\"parameters\"]) def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside =", "extra_point_types.items(): if k in classes_point_types: classes_point_types[k].append(v) else: classes_point_types[k] = v", "module_functions[(module, header)] header_classes = main_classes[(module, header)] methods_defined_outside = get_methods_defined_outside(header_functions) class_definitions", "Instantiations from generators.point_types_utils import unpack_yaml_point_types from generators.utils import make_header_include_name, sort_headers_by_dependencies,", "open(path, \"w\").write(files_to_write[path]) written.append(path) elif delete_others: os.remove(path) print(\"Deleted: \" + path)", "def generate_header(module, header, path, keep_if_no_instantiation) -> str: header_functions = module_functions[(module,", "namespaces = set([c[\"namespace\"] for c in main_classes]) for namespace in", "if type_ in param[\"type\"]: keep = False if keep: filtered.append(f)", "for module, classes in classes_by_module.items(): needs = [] for class_", "def generate(headers_to_generate, skip_macros, not_every_point_type=False) -> OrderedDict: \"\"\" :return: OrderedDict \"\"\"", "something_instantiated or keep_if_no_instantiation: text = [class_definitions, function_definitions, instantiation_function] return \"\\n\".join(text)", "METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES, \\ SPECIALIZED_TEMPLATED_TYPES_TO_SKIP from generators.definitions.function import generate_function_definitions, get_methods_defined_outside", "for class_ in main_classes: specialized_template = class_.get(\"template\") and \"<\" in", "None: skip_macros = [] header_file_str = read_header_file(header_path, skip_macros) parser =", "properties = filtered_properties return properties def get_main_classes(header, module, header_name): #", "def private_methods_defined_outside(private_methods: List[CppMethod], methods_declared_outside: List[CppMethod]) -> List[CppMethod]: private_defined_outside = []", "import platform import shutil import sys from collections import Counter", "header_name), \"\")) a(make_header_include_name(module, header_name, path)) a(\"\") namespaces = set([c[\"namespace\"] for", "set([m[\"name\"] for a in access for m in class_[\"methods\"][a] if", "return False # bug in CppHeaderParser # in \"void ImageGrabber<PointT>::publish\",", "method is not implemented all_implemented_inherited_methods = get_all_class_methods_not_pure_virtual(class_) namespace_class = make_namespace_class(class_[\"namespace\"],", "(module, header_name, class_[\"name\"]) in CLASSES_TO_IGNORE: pass else: filtered_main_classes.append(class_) filtered_main_classes =", "PATH_LOADER, PATH_MODULES, MODULES_TO_BUILD, \\ HEADERS_TO_SKIP, ATTRIBUTES_TO_SKIP, CLASSES_TO_IGNORE, METHODS_TO_SKIP, SUBMODULES_TO_SKIP, EXPLICIT_INCLUDES,", "= open(path).read() if v != text: print(\"File is different: %s\"", "class_[\"abstract\"]: can_be_instantiated = False else: # check if any pure" ]
[ "winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read()", "is stored in environment and you can get them by", "for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import", "winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- # All params", "# Load PS script from file and replace params winrm_wrapper.writeLog(\"loading", "sys, os # this is needed for importing file winrm_wrapper", "and you can get them by os.environ[\"paramName\"] import sys, os", "# All params from IdM is stored in environment and", "params from IdM is stored in environment and you can", "in environment and you can get them by os.environ[\"paramName\"] import", "needed for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..'))", "from file and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"],", "script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command", "os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for", "is needed for importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__),", "codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid)", "and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r')", "Load PS script from file and replace params winrm_wrapper.writeLog(\"loading script\")", "-*- coding: utf-8 -*- # All params from IdM is", "os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \"", "command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"],", "encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid) #", "'..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start", "file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import", "os.environ[\"paramName\"] import sys, os # this is needed for importing", "# Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command,", "winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\" + uid) sys.exit()", "winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load PS script", "from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid", "start for \" + uid) # Load PS script from", "-*- # All params from IdM is stored in environment", "by os.environ[\"paramName\"] import sys, os # this is needed for", "= command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"],", "uid) # Load PS script from file and replace params", "Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid)", "\" + uid) # Load PS script from file and", "codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\", uid)", "PS script from file and replace params winrm_wrapper.writeLog(\"loading script\") f", "them by os.environ[\"paramName\"] import sys, os # this is needed", "import sys, os # this is needed for importing file", "IdM is stored in environment and you can get them", "utf-8 -*- # All params from IdM is stored in", "params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command =", "os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load PS", "command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"],", "# -*- coding: utf-8 -*- # All params from IdM", "f.read() command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"],", "import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" +", "= os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) # Load", "os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid)", "+ uid) # Load PS script from file and replace", "All params from IdM is stored in environment and you", "wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete", "command = f.read() command = command.replace(\"$uid\", uid) # Call wrapper", "# this is needed for importing file winrm_wrapper from parent", "<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # All", "environment and you can get them by os.environ[\"paramName\"] import sys,", "from IdM is stored in environment and you can get", "winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs", "dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"]", "f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command =", "can get them by os.environ[\"paramName\"] import sys, os # this", "= codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command = f.read() command = command.replace(\"$uid\",", "parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid =", "= f.read() command = command.replace(\"$uid\", uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"],", "replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8', mode='r') command", "winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \"", "file and replace params winrm_wrapper.writeLog(\"loading script\") f = codecs.open(os.environ[\"script\"], encoding='utf-8',", "import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for", "stored in environment and you can get them by os.environ[\"paramName\"]", "script from file and replace params winrm_wrapper.writeLog(\"loading script\") f =", "uid) # Call wrapper winrm_wrapper.executeScript(os.environ[\"endpoint\"], os.environ[\"authentication\"], os.environ[\"user\"], os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"],", "uid) winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\" + uid)", "importing file winrm_wrapper from parent dir sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper", "command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\" +", "mode='r') command = f.read() command = command.replace(\"$uid\", uid) # Call", "sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import winrm_wrapper import codecs uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete", "for \" + uid) # Load PS script from file", "you can get them by os.environ[\"paramName\"] import sys, os #", "coding: utf-8 -*- # All params from IdM is stored", "uid = os.environ[\"__UID__\"] winrm_wrapper.writeLog(\"Delete start for \" + uid) #", "this is needed for importing file winrm_wrapper from parent dir", "os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" + uid) print(\"__UID__=\"", "os # this is needed for importing file winrm_wrapper from", "os.environ[\"password\"], os.environ[\"caTrustPath\"], os.environ[\"ignoreCaValidation\"], command, uid) winrm_wrapper.writeLog(\"Delete end for \" +", "python3 # -*- coding: utf-8 -*- # All params from", "get them by os.environ[\"paramName\"] import sys, os # this is" ]
[ "in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in", "class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value,", "ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase): def", "ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def", "self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def", "aenum import Enum, auto from dace import registry @registry.make_registry class", "class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension", "def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension],", "pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2)", "Enum, auto from dace import registry @registry.make_registry class ExtensibleClass(object): pass", "self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self):", "self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__ == '__main__': unittest.main()", "in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class", "pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto()", "class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b", "ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass):", "= auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions())", "def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions())", "auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension", "All rights reserved. import unittest from aenum import Enum, auto", "import unittest from aenum import Enum, auto from dace import", "from dace import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass):", "self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension", "test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3],", "def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in", "Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3)", "a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2))", "c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension", "test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c')", "self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not", "pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with", "self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass):", "pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def", "b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0))", "class ExtensibleEnumeration(Enum): a = auto() b = auto() class RegistryTests(unittest.TestCase):", "def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__", "ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in", "import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum", "= auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension)", "ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class", "test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__ ==", "authors. All rights reserved. import unittest from aenum import Enum,", "c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0)", "@registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration)", "2019-2021 ETH Zurich and the DaCe authors. All rights reserved.", "b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False,", "test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with", "self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass", "registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class", "test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions())", "Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1,", "class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a", "pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto()", "self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum", "ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class", "from aenum import Enum, auto from dace import registry @registry.make_registry", "@registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b = auto() class", "class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def", "in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in", "ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object):", "Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights", "unittest from aenum import Enum, auto from dace import registry", "Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a = auto() b =", "ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions())", "ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class", "auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension)", "@registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension,", "in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister", "import Enum, auto from dace import registry @registry.make_registry class ExtensibleClass(object):", "ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum): a =", "def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self):", "reserved. import unittest from aenum import Enum, auto from dace", "self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object):", "class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True,", "ETH Zurich and the DaCe authors. All rights reserved. import", "a = auto() b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self):", "@registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass @registry.extensible_enum class ExtensibleEnumeration(Enum):", "not in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass", "def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def", "self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass", "with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c", "def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self):", "self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def test_enum_registry(self): ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in", "RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not", "ExtensibleEnumeration.register('c') self.assertTrue(ExtensibleEnumeration.c in ExtensibleEnumeration) self.assertEqual(ExtensibleEnumeration.c.value, 3) def test_enum_registry_fail(self): with self.assertRaises(TypeError):", "dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass", "b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError): @registry.autoregister class Extension4(object): pass def", "self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self): with self.assertRaises(TypeError):", "b = auto() class RegistryTests(unittest.TestCase): def test_class_registry(self): ExtensibleClass.register(Extension) self.assertTrue(Extension in", "and the DaCe authors. All rights reserved. import unittest from", "not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2", "Zurich and the DaCe authors. All rights reserved. import unittest", "ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions())", "DaCe authors. All rights reserved. import unittest from aenum import", "auto from dace import registry @registry.make_registry class ExtensibleClass(object): pass class", "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All", "test_autoregister(self): @registry.autoregister class Extension2(ExtensibleClass): pass self.assertTrue(Extension2 in ExtensibleClass.extensions()) def test_class_registry_args(self):", "b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension)", "in ExtensibleClass.extensions()) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister(self): @registry.autoregister", "dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions()) def test_autoregister_args(self):", "ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1, c=2)) ExtensibleClass.unregister(Extension) self.assertTrue(Extension not in ExtensibleClass.extensions())", "in ExtensibleClass.extensions()) def test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in", "ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True, b=1,", "in ExtensibleClass.extensions()) def test_autoregister_args(self): @registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3", "dace import registry @registry.make_registry class ExtensibleClass(object): pass class Extension(ExtensibleClass): pass", "test_class_registry_args(self): ExtensibleClass.register(Extension, a=True, b=1, c=2) self.assertTrue(Extension in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension], dict(a=True,", "with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if __name__ == '__main__':", "the DaCe authors. All rights reserved. import unittest from aenum", "rights reserved. import unittest from aenum import Enum, auto from", "Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False, b=0)) def test_autoregister_fail(self):", "@registry.autoregister_params(a=False, b=0) class Extension3(ExtensibleClass): pass self.assertTrue(Extension3 in ExtensibleClass.extensions()) self.assertEqual(ExtensibleClass.extensions()[Extension3], dict(a=False,", "3) def test_enum_registry_fail(self): with self.assertRaises(TypeError): @registry.extensible_enum class NotAnEnum(object): pass if" ]
[ "for fut in self.futs: if not fut.done(): fut.set_result(None) async def", "start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return", "for i in s.split(\"\\n\") if i] async def close(self): if", "s.split(\"\\n\") if i] async def close(self): if self.server is None:", "if self.server is None: return self.server.close() await self.server.wait_closed() self.server =", "def on_connect(self, reader, writer): while True: data = await reader.read(1024)", "break self.data.extend(data) for fut in self.futs: if not fut.done(): fut.set_result(None)", "finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async def", "self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1]", "setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server = await make_tcp_handler(*args,", "**kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler, server yield", "def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG, **kwargs):", "if i] async def close(self): if self.server is None: return", "self.server is None: return self.server.close() await self.server.wait_closed() self.server = None", "async def finalize(): for server in servers: await server.close() await", "await self.server.wait_closed() self.server = None async def on_connect(self, reader, writer):", "pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self):", "host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s", "= FakeTcpServer() await server.start() servers.append(server) return server yield go async", "await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async", "go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler = await", "self.server.wait_closed() self.server = None async def on_connect(self, reader, writer): while", "not data: break self.data.extend(data) for fut in self.futs: if not", "make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler,", "asyncio import logging from json import loads import pytest from", "on_connect(self, reader, writer): while True: data = await reader.read(1024) if", "asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers", "import asyncio import logging from json import loads import pytest", "loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer:", "import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def", "async def go(): server = FakeTcpServer() await server.start() servers.append(server) return", "@property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s =", "def close(self): if self.server is None: return self.server.close() await self.server.wait_closed()", "not fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut)", "**kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\")", "fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = [] async", "server.port, **kwargs) handlers.append(handler) return handler, server yield go async def", "if not fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future()", "None async def on_connect(self, reader, writer): while True: data =", "bytearray() self.server = None self.futs = set() async def start(self):", "return [loads(i) for i in s.split(\"\\n\") if i] async def", "fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut", "server yield go async def finalize(): for server in servers:", "for server in servers: await server.close() await finalize() @pytest.fixture async", "import logging from json import loads import pytest from aiologstash2", "reader, writer): while True: data = await reader.read(1024) if not", "handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args,", "FakeTcpServer: def __init__(self): self.data = bytearray() self.server = None self.futs", "fut.done(): fut.set_result(None) async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await", "await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = []", "server.start() servers.append(server) return server yield go async def finalize(): for", "for handler in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture", "async def go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs)", "handlers = [] async def go(*args, level=logging.DEBUG, **kwargs): server =", "= await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler)", "s = self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if", "await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield go", "wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async", "@property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i", "make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG, **kwargs): server", "make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler, server", "go async def finalize(): for server in servers: await server.close()", "def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i in", "logging from json import loads import pytest from aiologstash2 import", "self.futs: if not fut.done(): fut.set_result(None) async def wait(self): fut =", "= [] async def go(): server = FakeTcpServer() await server.start()", "async def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args, level=logging.DEBUG,", "return server yield go async def finalize(): for server in", "[] async def go(): server = FakeTcpServer() await server.start() servers.append(server)", "FakeTcpServer() await server.start() servers.append(server) return server yield go async def", "finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler,", "async def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut)", "= await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield", "self.server = None async def on_connect(self, reader, writer): while True:", "yield go async def finalize(): for handler in handlers: handler.close()", "def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self):", "reader.read(1024) if not data: break self.data.extend(data) for fut in self.futs:", "@pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server", "handlers.append(handler) return handler, server yield go async def finalize(): for", "server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = []", "json import loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG)", "def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\")", "servers.append(server) return server yield go async def finalize(): for server", "await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return", "server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return", "handler in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async", "self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers = [] async def", "= [] async def go(*args, level=logging.DEBUG, **kwargs): server = await", "await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler,", "server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs)", "handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler):", "logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray() self.server =", "await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers =", "self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if i] async", "= None async def on_connect(self, reader, writer): while True: data", "= set() async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\")", "in handlers: handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def", "self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for", "async def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler", "finalize(): for server in servers: await server.close() await finalize() @pytest.fixture", "go async def finalize(): for handler in handlers: handler.close() await", "is None: return self.server.close() await self.server.wait_closed() self.server = None async", "= None self.futs = set() async def start(self): self.server =", "create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server yield go async", "logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger, handler, server yield go", "@pytest.fixture async def make_tcp_handler(make_tcp_server): handlers = [] async def go(*args,", "from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data", "writer): while True: data = await reader.read(1024) if not data:", "self.data = bytearray() self.server = None self.futs = set() async", "import loads import pytest from aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class", "await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def", "self.data.extend(data) for fut in self.futs: if not fut.done(): fut.set_result(None) async", "= bytearray() self.server = None self.futs = set() async def", "async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def", "**kwargs): server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\", server.port,", "return handler, server yield go async def finalize(): for handler", "self.futs = set() async def start(self): self.server = await asyncio.start_server(self.on_connect,", "async def on_connect(self, reader, writer): while True: data = await", "self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server(): servers =", "[] async def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server()", "await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def go(*args, **kwargs):", "servers: await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server): handlers", "def finalize(): for handler in handlers: handler.close() await handler.wait_closed() await", "if not data: break self.data.extend(data) for fut in self.futs: if", "fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def", "handler.close() await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async", "def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server = await", "async def make_tcp_server(): servers = [] async def go(): server", "return self.server.close() await self.server.wait_closed() self.server = None async def on_connect(self,", "import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray()", "= self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\") if i]", "handler, server = await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler)", "return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return [loads(i)", "finalize(): for handler in handlers: handler.close() await handler.wait_closed() await finalize()", "self.server = None self.futs = set() async def start(self): self.server", "port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self): s = self.data.decode(\"utf8\") return", "make_tcp_server(): servers = [] async def go(): server = FakeTcpServer()", "= await reader.read(1024) if not data: break self.data.extend(data) for fut", "async def close(self): if self.server is None: return self.server.close() await", "go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger =", "i in s.split(\"\\n\") if i] async def close(self): if self.server", "server = FakeTcpServer() await server.start() servers.append(server) return server yield go", "while True: data = await reader.read(1024) if not data: break", "in self.futs: if not fut.done(): fut.set_result(None) async def wait(self): fut", "level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler = await create_tcp_handler(\"127.0.0.1\",", "server in servers: await server.close() await finalize() @pytest.fixture async def", "await server.start() servers.append(server) return server yield go async def finalize():", "def make_tcp_server(): servers = [] async def go(): server =", "server yield go async def finalize(): for handler in handlers:", "def go(*args, **kwargs): handler, server = await make_tcp_handler(*args, **kwargs) logger", "await handler.wait_closed() await finalize() @pytest.fixture async def setup_logger(make_tcp_handler): async def", "def wait(self): fut = asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture", "data: break self.data.extend(data) for fut in self.futs: if not fut.done():", "= await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property", "await reader.read(1024) if not data: break self.data.extend(data) for fut in", "True: data = await reader.read(1024) if not data: break self.data.extend(data)", "jsons(self): s = self.data.decode(\"utf8\") return [loads(i) for i in s.split(\"\\n\")", "i] async def close(self): if self.server is None: return self.server.close()", "data = await reader.read(1024) if not data: break self.data.extend(data) for", "def go(*args, level=logging.DEBUG, **kwargs): server = await make_tcp_server() handler =", "async def setup_logger(make_tcp_handler): async def go(*args, **kwargs): handler, server =", "from json import loads import pytest from aiologstash2 import create_tcp_handler", "**kwargs) handlers.append(handler) return handler, server yield go async def finalize():", "in s.split(\"\\n\") if i] async def close(self): if self.server is", "set() async def start(self): self.server = await asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property", "handler = await create_tcp_handler(\"127.0.0.1\", server.port, **kwargs) handlers.append(handler) return handler, server", "asyncio.start_server(self.on_connect, host=\"127.0.0.1\") @property def port(self): return self.server.sockets[0].getsockname()[1] @property def jsons(self):", "close(self): if self.server is None: return self.server.close() await self.server.wait_closed() self.server", "servers = [] async def go(): server = FakeTcpServer() await", "aiologstash2 import create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data =", "None: return self.server.close() await self.server.wait_closed() self.server = None async def", "go(): server = FakeTcpServer() await server.start() servers.append(server) return server yield", "in servers: await server.close() await finalize() @pytest.fixture async def make_tcp_handler(make_tcp_server):", "yield go async def finalize(): for server in servers: await", "self.server.close() await self.server.wait_closed() self.server = None async def on_connect(self, reader,", "@pytest.fixture async def make_tcp_server(): servers = [] async def go():", "create_tcp_handler logging.getLogger().setLevel(logging.DEBUG) class FakeTcpServer: def __init__(self): self.data = bytearray() self.server", "__init__(self): self.data = bytearray() self.server = None self.futs = set()", "def go(): server = FakeTcpServer() await server.start() servers.append(server) return server", "class FakeTcpServer: def __init__(self): self.data = bytearray() self.server = None", "def finalize(): for server in servers: await server.close() await finalize()", "= await make_tcp_handler(*args, **kwargs) logger = logging.getLogger(\"aiologstash_test\") logger.addHandler(handler) return logger,", "fut in self.futs: if not fut.done(): fut.set_result(None) async def wait(self):", "None self.futs = set() async def start(self): self.server = await", "[loads(i) for i in s.split(\"\\n\") if i] async def close(self):", "async def finalize(): for handler in handlers: handler.close() await handler.wait_closed()", "= asyncio.get_event_loop().create_future() self.futs.add(fut) await fut self.futs.remove(fut) @pytest.fixture async def make_tcp_server():", "handler, server yield go async def finalize(): for handler in", "def __init__(self): self.data = bytearray() self.server = None self.futs =" ]
[ "before int as python says a bool is an int", "None: self.log.warning('The key is None.') return None # get variable", "Array.\"\"\" for d in data: if not self._is_tc_entity(d): return False", "in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided", "not isinstance(value, bytes): # value = value.encode('utf-8') if validate and", "the string. value = re.sub(variable, v, value) return value @property", "it's a list (as opposed to an iterable) if variable_type", "Variables can only be embedded one level deep. This method", "'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of standard playbook", "Value.\"\"\" if data is None: return False return all(x in", "None self._output_variables_by_type = None self.log = tcex.log # match full", "null value for key was provided.') return None # get", "{ \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\",", "if validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data", "to say if value is just the variable reference, #", "def _is_key_value(data): \"\"\"Return True if provided data has proper structure", "value = self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value))", "class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx):", "data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover #", "data (str): The data with embedded variables. Returns: (str): Results", "value def parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder", "(TcEx): Instance of TcEx class. context (str): The Redis context", "Module Base Class Args: tcex (TcEx): Instance of TcEx class.", "str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value})", "reformat to replace the correct instance only, handling the case", "== 'KeyValue': # embedded variable can be unquoted, which breaks", "Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {}", "_read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis", "string with value retrieved from DB. If there are no", "instead of just the string. value = re.sub(variable, v, value)", "needs to be searched for embedded variables. Embedded variable rules:", "embedded variables. * Only String and KeyValueArray variables can have", "string values v = self._coerce_string_value(v) if validate and not isinstance(v,", "Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate", "try: value = json.dumps(value) except ValueError as e: # pragma:", "to str type self.log.warning(f'Coercing bool value ({value}) to a string", "JSON data. Returns: any: The de-serialized value from the key/value", "value = re.sub(variable, v, value) return value @property def _variable_pattern(self):", "type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to", "RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create - context:", "value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray': if validate", "def _create_array(self, key, value, validate=True): \"\"\"Create the value in Redis", "self.log.warning('The null value for key was provided.') return None #", "to be searched for embedded variables. Embedded variable rules: *", "key is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The", "key.strip()) else: self.log.warning('The key field was None.') return value def", "value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except", "raw data. ..important:: Bytes input will be returned a as", "collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class", "#App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This", "# spread the value so that we know it's a", "data to write to the DB. Returns: (str): Result of", "self.log.warning('The key or value field is None.') return None #", "proper structure for Key Value.\"\"\" if data is None: return", "data is not None: # pragma: no cover variables =", "Entity Array.\"\"\" for d in data: if not self._is_tc_entity(d): return", "try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: #", "and not isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.')", "\"\"\"Return the loaded JSON value or raise an error. Args:", "write. \"\"\" data = None if key is not None", "is an int if isinstance(value, bool): # coerce bool to", "= data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover # for", "values elif variable_type == 'KeyValueArray': # embedded variable can be", "output_variables (list): The requested output variables. \"\"\" def __init__(self, tcex,", "or needs to be searched for embedded variables. Embedded variable", "Returns: (str): Results retrieved from DB \"\"\" # TODO: need", "= self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value) return", "= str(value) return value def _create(self, key, value, validate=True): \"\"\"Create", "= re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded", "embedded: value = self._read_embedded(value) value = self._load_value(value) elif variable_type ==", "etc) must be serialized. Args: key (str): The variable to", "_load_value(value): \"\"\"Return the loaded JSON value or raise an error.", "@staticmethod def _is_key_value(data): \"\"\"Return True if provided data has proper", "'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of", "value: if v is not None and b64decode: v =", "TODO: need to verify if core still sends improper JSON", "# coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type", "returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray:", "this method that gets the entire list/dict instead of just", "key.strip(), value) except RuntimeError as e: self.log.error(e) return None def", "same key value array. data = data.replace(var, f'\": \"{variable_string}\"') return", "string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray',", "r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable", "self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') try:", "str value_coerced = [] for v in self._load_value(value): # coerce", "a byte, str or int. Other data structures (dict, list,", "the DB. Returns: (str): Results retrieved from DB. \"\"\" value", "KeyValueArray.') elif variable_type == 'StringArray': value_coerced = [] for v", "has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"]", "Instance of TcEx class. context (str): The Redis context (hash).", "variable can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value)", "not None: if validate and not isinstance(v, bytes): raise RuntimeError('Invalid", "applicable.\"\"\" if key is None: # pragma: no cover self.log.warning('The", "array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder for child", "of CRUD operation for raw data. ..important:: Bytes input will", "variable to get individual parts parsed_variable = self.parse_variable(ov) variable_name =", "= self.variable_type(key) if variable_type == 'Binary': # if not isinstance(value,", "else: self.log.warning('The key field was None.') return value def parse_variable(self,", "v in value: if v is not None and b64decode:", "try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e)", "create - context: {self._context}, key: {key}, value: {value}') try: value", "version of this method that gets the entire list/dict instead", "data structures (dict, list, etc) must be serialized. Args: key", "value): \"\"\"Create method of CRUD operation for raw data. ..important::", "for KeyValueArray.') elif variable_type == 'StringArray': value_coerced = [] for", "store. Raises: RuntimeError: Raise error when data can't be loaded", "key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if", "if validate and not isinstance(value, str): raise RuntimeError('Invalid data provided", "from the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except", "3: Input: [{ \"key\": \"embedded string\", \"value\": \"This input has", "values = [] for v in value: if v is", "if provided data has proper structure for Key Value.\"\"\" if", "= base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type ==", "no cover raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).')", "insert '' in string. That would require a kv-specific #", "Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{", "for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if", "handling the case where a variable # is embedded multiple", "the resulting data is loadable JSON value = re.sub(f'\"{variable}\"', v,", "this to handle variable references in kv/kvarrays that # are", "= value_encoded elif variable_type == 'KeyValueArray': if validate and not", "parsed and updated from the DB. Returns: (str): Results retrieved", "set to handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String)", "x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True", "if b64decode: value = base64.b64decode(value) if decode: value = self._decode_binary(value)", "= tcex self._context = context self._output_variables = output_variables or []", "automatically determine if the input is a variable or needs", "are None. Would like to be able to say if", "value = value_coerced elif variable_type == 'TCEntityArray': if validate and", "= context self._output_variables = output_variables or [] # properties self._output_variables_by_name", "RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced", "know it's a list (as opposed to an iterable) if", "custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern", "RuntimeError as e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return", "None: return value if variable_type == 'Binary': value = self._load_value(value)", "if validate and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise", "= str(value).lower() # coerce int to str type if isinstance(value,", "Redis if applicable.\"\"\" if key is None: # pragma: no", "The ``read()`` method will automatically determine if the input is", "= self._coerce_string_value(value) if validate and not isinstance(value, str): raise RuntimeError('Invalid", "def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double quotes.", "raise NotImplementedError('Implemented in child class') def read(self, key, array=False, embedded=True):", "to a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int", "be able to say if value is just the variable", "APP-1030 need to revisit this to handle variable references in", "def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in", "a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without", "except RuntimeError as e: self.log.error(e) return None def _create_array(self, key,", "value_encoded elif variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value):", "['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create -", "object_pairs_hook=OrderedDict) values = [] for v in value: if v", "raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create -", "for v in value: # coerce string values v =", "variable_type == 'TCEntity': if validate and (not isinstance(value, dict) or", "\"\"\"Create method of CRUD operation for raw data. ..important:: Raw", "def _parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook Class.", "operation for raw data. ..important:: Raw data can only be", "(str): The variable to write to the DB. value (bytes|int|string):", "is None: self.log.warning('The key or value field is None.') return", "* Only user input can have embedded variables. * Only", "no keys/variables the raw string will be returned. Examples:: DB", "\"\"\" if value is None: # pragma: no cover return", "ov in self._output_variables: # parse the variable to get individual", "we know it's a list (as opposed to an iterable)", "variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ]", "not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError", "key (str): The variable to read from the DB. Returns:", "# variable type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return", "base64 import json import re from collections import OrderedDict from", "has proper structure for TC Entity Array.\"\"\" for d in", "no cover raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})')", "over set to handle duplicates # pull (#App:1441:embedded_string!String) from (\":", "#App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded string\", \"value\":", "like to be able to say if value is just", "+= r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' #", "variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable':", "Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\",", "= {} for ov in self._output_variables: # parse the variable", "value so that we know it's a list (as opposed", "data = data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True", "data has proper structure for TC Entity Array.\"\"\" for d", "coerce bool to str type self.log.warning(f'Coercing bool value ({value}) to", "value in Redis if applicable.\"\"\" if key is None: self.log.warning('The", "return None # get variable type from variable value variable_type", "serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError", "self.log.warning('The key is None.') return None # get variable type", "not None and value is not None: try: data =", "string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int to str", "'Binary': value = self._load_value(value) if b64decode: value = base64.b64decode(value) if", "= self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)): raise", "(str): Results retrieved from DB \"\"\" # TODO: need to", "updated from the DB. Returns: (str): Results retrieved from DB", "embedded: value = self._read_embedded(value) # convert int to str value_coerced", "of DB write. \"\"\" data = None if key is", "in the same key value array. data = data.replace(var, f'\":", "else insert '' in string. That would require a kv-specific", "self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return None", "return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data", "with embedded variables. Returns: (str): Results retrieved from DB \"\"\"", "method will automatically covert variables embedded in a string with", "from variable value variable_type = self.variable_type(key) if variable_type == 'Binary':", "return value def parse_variable(self, variable): # pragma: no cover \"\"\"Set", "is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key", "int.\"\"\" # coerce bool before int as python says a", "= parsed_variable.get('type') # store the variables in dict by name", "to revisit this to handle variable references in kv/kvarrays that", "not isinstance(value, str): raise RuntimeError('Invalid data provided for String.') elif", "[] for v in value: # coerce string values v", "tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture", "isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v)", "wild-wild west, don't validate it if variable_type != 'TCEnhancedEntityArray': if", "None.') return data def read_raw(self, key): \"\"\"Read method of CRUD", "coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in", "match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts", "{variable}, value: {v}') if isinstance(v, (dict, list)): v = json.dumps(v)", "re from collections import OrderedDict from collections.abc import Iterable class", "self.variable_type(key) if variable_type == 'Binary': # if not isinstance(value, bytes):", "name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key,", "value_coerced elif variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value):", "match literal (#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)'", "provided for Binary.') # if not isinstance(v, bytes): # v", "DB \"\"\" if value is None: # pragma: no cover", "dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.')", "java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma:", "opposed to an iterable) if variable_type == 'BinaryArray': value_encoded =", "[ *value ] # spread the value so that we", "key value array. data = data.replace(var, f'\": \"{variable_string}\"') return data", "elif variable_type == 'KeyValue': if validate and (not isinstance(value, dict)", "breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value)", "validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided", "self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return None if", "dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} #", "returned from kv store # APP-1030 need to revisit this", "= self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return None", ".. Note:: The ``read()`` method will automatically determine if the", "in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced", "# is embedded multiple times in the same key value", "(str): Results retrieved from DB. \"\"\" value = None if", "is not None: # only replace variable if a non-null", "v, value) if v is not None: # only replace", "variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray'", "from DB. If there are no keys/variables the raw string", "*value ] # spread the value so that we know", "data. ..important:: Bytes input will be returned a as string", "[\"one\", \"two\", \"three\"] Examples 1: Input: \"This input has a", "'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return", "data for x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data):", "Result of DB write. \"\"\" data = None if key", "the input is a variable or needs to be searched", "CRUD operation for raw data. ..important:: Raw data can only", "context: {self._context}, key: {key}, value: {value}') return value def _read_embedded(self,", "str): raise RuntimeError('Invalid data provided for String.') elif variable_type ==", "return False return True @staticmethod def _load_value(value): \"\"\"Return the loaded", "True if provided data has proper structure for TC Entity.\"\"\"", "= self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value)) elif", "input has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\",", "if isinstance(value, bool): # coerce bool to str type self.log.warning(f'Coercing", "if validate and not isinstance(v, bytes): raise RuntimeError('Invalid data provided", "return None if value is None: return value if variable_type", "variable_type = parsed_variable.get('type') # store the variables in dict by", "value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as", "(bytes|int|string): The data to write to the DB. Returns: (str):", "v, value) return value @property def _variable_pattern(self): \"\"\"Regex pattern to", "RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create - context:", "as JSON data. Returns: any: The de-serialized value from the", "- context: {self._context}, key: {key}, value: {value}') return value def", "re.search(self._variable_parse, var).group(0) # reformat to replace the correct instance only,", "String.') elif variable_type == 'TCEntity': if validate and (not isinstance(value,", "for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom", "provided for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type ==", "for String.') elif variable_type == 'TCEntity': if validate and (not", "name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the", "and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif", "need to verify if core still sends improper JSON for", "v = self._decode_binary(v) values.append(v) value = values elif variable_type ==", "is not None: # pragma: no cover variables = []", "in set(variables): # recursion over set to handle duplicates #", "self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value) return value", "float/int value ({value}) to a string (\"{str(value)}\").') value = str(value)", "Examples 1: Input: \"This input has a embedded #App:7979:variable_name!String\" Examples", "value for variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))):", "bytes): raise RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8')", "(v.group(0) for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded", "output variables provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String',", "in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value:", "entity array is the wild-wild west, don't validate it if", "elif variable_type == 'TCEntity': value = self._load_value(value) return value def", "= self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key: {key},", "Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type =", "key: {key}, value: {value}') return value def _read_embedded(self, value): \"\"\"Read", "return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def", "value = self._load_value(value) elif variable_type == 'String': if embedded: value", "variables. .. Note:: The ``read()`` method will automatically determine if", "variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = []", "'StringArray': if embedded: value = self._read_embedded(value) # convert int to", "# non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non", "'String': if embedded: value = self._read_embedded(value) # coerce string values", "(dict, list)): v = json.dumps(v) # for KeyValueArray with nested", "isinstance(value, str): raise RuntimeError('Invalid data provided for String.') elif variable_type", "string. That would require a kv-specific # version of this", "way to determine data from redis originated as bytes or", "convert int to str value_coerced = [] for v in", "value retrieved from DB. If there are no keys/variables the", "that # are None. Would like to be able to", "data def read_raw(self, key): \"\"\"Read method of CRUD operation for", "Only user input can have embedded variables. * Only String", "'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided data has", "sub None value, else insert '' in string. That would", "key is None or value is None: self.log.warning('The key or", "redis originated as bytes or string. Args: key (str): The", "variable references in kv/kvarrays that # are None. Would like", "\"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This input", "to the DB. Returns: (str): Result of DB write. \"\"\"", "None.') return value def parse_variable(self, variable): # pragma: no cover", "{} for ov in self._output_variables: # parse the variable to", "raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif variable_type", "gets the entire list/dict instead of just the string. value", "types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property", "= base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and (not", "properties self._output_variables_by_name = None self._output_variables_by_type = None self.log = tcex.log", "is embedded multiple times in the same key value array.", "string will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\"", "non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type", "variable_type == 'StringArray': value_coerced = [] for v in value:", "{'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the", "= self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value = self._load_value(value)", "string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\" }, {", "can only be a byte, str or int. Other data", "of just the string. value = re.sub(variable, v, value) return", "field is None.') return None # get variable type from", "RuntimeError as e: self.log.error(e) else: self.log.warning('The key or value field", "= self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as", "@property def _variable_pattern(self): \"\"\"Regex pattern to match and parse a", "literal (#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)' #", "variable_type == 'Binary': value = self._load_value(value) if b64decode: value =", "re.sub(f'\"{variable}\"', v, value) if v is not None: # only", "loaded as JSON data. Returns: any: The de-serialized value from", "variable value variable_type = self.variable_type(key) if variable_type == 'Binary': #", "(not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data", "if embedded: value = self._read_embedded(value) # coerce string values value", "= json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in value:", "\"\"\"Return decoded bytes data handling data written by java apps.\"\"\"", "multiple times in the same key value array. data =", "self._output_variables: # parse the variable to get individual parts parsed_variable", "# app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name", "variable value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip())", "for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return", "is just the variable reference, # sub None value, else", "user input can have embedded variables. * Only String and", "value = self._load_value(value) if b64decode: value = base64.b64decode(value) if decode:", "elif variable_type == 'KeyValueArray': # embedded variable can be unquoted,", "pragma: no cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded,", "(exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables", "self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray)", "improper JSON for KeyValueArrays if data is not None: #", "bytes): raise RuntimeError('Invalid data provided for Binary.') # if not", "- context: {self._context}, key: {key}, value: {value}') try: value =", "in value: # coerce string values v = self._coerce_string_value(v) if", "b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if", "self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e:", "] # spread the value so that we know it's", "None and b64decode: v = base64.b64decode(v) if decode: v =", "self._load_value(value) elif variable_type == 'String': if embedded: value = self._read_embedded(value)", "embedded variable in double quotes. Args: data (str): The data", "data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True if provided", "is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except", "coerce string values value = self._coerce_string_value(value) if validate and not", "JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value", "JSON value or raise an error. Args: value (str): The", "return value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the", "variable value variable_type = self.variable_type(key) # Enhanced entity array is", "so that we know it's a list (as opposed to", "or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif", "data provided for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type", "for TC Entity.\"\"\" if data is None: return False return", "= v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif", "'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list", "\"\"\"Read method of CRUD operation for raw data. ..important:: Bytes", "value (bytes|int|string): The data to write to the DB. Returns:", "variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value):", "the wild-wild west, don't validate it if variable_type != 'TCEnhancedEntityArray':", "DB. Returns: (str): Results retrieved from DB. \"\"\" value =", "cover self.log.warning('The null value for key was provided.') return None", "value = str(value) return value def _create(self, key, value, validate=True):", "for variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v", "\"\"\"TcEx Framework Playbook module\"\"\" # standard library import base64 import", "by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self,", "not isinstance(v, bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8')", "provided data has proper structure for TC Entity.\"\"\" if data", "data provided for KeyValue.') elif variable_type == 'String': # coerce", "b64decode: v = base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v)", "[] # properties self._output_variables_by_name = None self._output_variables_by_type = None self.log", "dict/list type replace the # quoted value to ensure the", "value (str): The data from key/value store. Raises: RuntimeError: Raise", "from variable value variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context,", "(\"{str(value).lower()}\").') value = str(value).lower() # coerce int to str type", "for v in value: if v is not None and", "import json import re from collections import OrderedDict from collections.abc", "can have embedded variables. * Variables can only be embedded", "'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided data has", "\"embedded string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\" },", "(\"{str(value)}\").') value = str(value) return value def _create(self, key, value,", "if applicable.\"\"\" if key is None or value is None:", "or [] # properties self._output_variables_by_name = None self._output_variables_by_type = None", "_is_tc_entity(data): \"\"\"Return True if provided data has proper structure for", "bytes data handling data written by java apps.\"\"\" try: data", "# value = value.encode('utf-8') if validate and not isinstance(value, bytes):", "to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name", "raise RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif", "list/dict instead of just the string. value = re.sub(variable, v,", "provided for String.') elif variable_type == 'TCEntity': if validate and", "for data written an upstream java App data = data.decode('latin-1')", "RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value)", "raise NotImplementedError('Implemented in child class') def variable_type(self, variable): # pragma:", "value is just the variable reference, # sub None value,", "array. data = data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self,", "r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable", "Playbook module\"\"\" # standard library import base64 import json import", "individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type =", "self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type ==", "self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value = json.loads(value,", "Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name =", "output_variables or [] # properties self._output_variables_by_name = None self._output_variables_by_type =", "'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or isinstance(value, (str,", "(e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables", "# only replace variable if a non-null value is returned", "and value is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(),", "variable in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v =", "v is not None: if validate and not isinstance(v, bytes):", "parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal", "if not self._is_tc_entity(d): return False return True @staticmethod def _load_value(value):", "# non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable", "Class properties.\"\"\" self.tcex = tcex self._context = context self._output_variables =", "import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args:", "structure for TC Entity Array.\"\"\" for d in data: if", "= base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray':", "class') def read(self, key, array=False, embedded=True): # pragma: no cover", "value variable_type = self.variable_type(key) if variable_type == 'Binary': # if", "= self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable can", "values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value =", "v = self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)):", "array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }]", "for raw data. ..important:: Raw data can only be a", "for \"embedded\" variables. .. Note:: The ``read()`` method will automatically", "variables. * Variables can only be embedded one level deep.", "embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3:", "be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded:", "value def _create(self, key, value, validate=True): \"\"\"Create the value in", "from an bool or int.\"\"\" # coerce bool before int", "handle variable references in kv/kvarrays that # are None. Would", "a list (as opposed to an iterable) if variable_type ==", "(not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided", "{key}, value: {value}') try: value = json.dumps(value) except ValueError as", "match and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' #", "# reformat to replace the correct instance only, handling the", "a string with value retrieved from DB. If there are", "'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create - context: {self._context},", "value to parsed and updated from the DB. Returns: (str):", "e: self.log.error(e) else: self.log.warning('The key or value field was None.')", "serialized. Args: key (str): The variable to write to the", "value) return value @property def _variable_pattern(self): \"\"\"Regex pattern to match", "upstream java App data = data.decode('latin-1') return data @staticmethod def", "value variable_type = self.variable_type(key) # Enhanced entity array is the", "(type(None), str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value", "elif variable_type == 'StringArray': value_coerced = [] for v in", "cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0))", "re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): # recursion over", "= self.variable_type(key) # Enhanced entity array is the wild-wild west,", "value: if v is not None: if validate and not", "Input: \"This input has a embedded #App:7979:variable_name!String\" Examples 2: Input:", "self.log.error(e) return None if value is None: return value if", "value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The key or", "store # APP-1030 need to revisit this to handle variable", "has proper structure for Key Value.\"\"\" if data is None:", "resulting data is loadable JSON value = re.sub(f'\"{variable}\"', v, value)", "None self.log = tcex.log # match full variable self._variable_match =", "= self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store", "data: if not self._is_tc_entity(d): return False return True @staticmethod def", "value = re.sub(f'\"{variable}\"', v, value) if v is not None:", "re.sub(variable, v, value) return value @property def _variable_pattern(self): \"\"\"Regex pattern", "+ self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in", "double quotes. Args: data (str): The data with embedded variables.", "Error: ({e})') elif variable_type == 'StringArray': if embedded: value =", "= re.search(self._variable_parse, var).group(0) # reformat to replace the correct instance", "}] Args: value (str): The value to parsed and updated", "String variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern +=", "value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if", "self.log.error(e) else: self.log.warning('The key or value field was None.') return", "a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples", "{} self._output_variables_by_type = {} for ov in self._output_variables: # parse", "provided.') return None # get variable type from variable value", "(str): The variable to read from the DB. Returns: (str):", "and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match", "for v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value", "only be a byte, str or int. Other data structures", "'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided", "pragma: no cover raise RuntimeError(f'Failed to serialize value ({e}).') try:", "except RuntimeError as e: self.log.error(e) else: self.log.warning('The key or value", "True if provided data has proper structure for TC Entity", "v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): #", "isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to a string", "value: {value}') return value def _read_embedded(self, value): \"\"\"Read method for", "return value if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict)", "self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").') value =", "Args: key (str): The variable to read from the DB.", "v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type", "(float, int)): self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").')", "embedded variables. Embedded variable rules: * Only user input can", "__init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex =", "value = self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True,", "RuntimeError(f'Invalid data provided for {variable_type}.') value = [ *value ]", "\"\"\"Return list of standard playbook array variable types.\"\"\" return [", "({value}) to a string (\"{str(value)}\").') value = str(value) return value", "\\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input:", "+= r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' #", "isinstance(v, bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v)", "coerce string values v = self._coerce_string_value(v) if validate and not", "None.') return None # get variable type from variable value", "variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match", "@staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data has proper", "return data @staticmethod def _is_key_value(data): \"\"\"Return True if provided data", "and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data", "get variable type from variable value variable_type = self.variable_type(key) try:", "# sub None value, else insert '' in string. That", "single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity',", "_create_array(self, key, value, validate=True): \"\"\"Create the value in Redis if", "in (v.group(0) for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable)", "base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type == 'KeyValueArray': if", "KeyValueArray variables can have embedded variables. * Variables can only", "replace the correct instance only, handling the case where a", "data provided for {variable_type}.') value = [ *value ] #", "(str): The data from key/value store. Raises: RuntimeError: Raise error", "TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value:", "child method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self, variable):", "return True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON value", "# pragma: no cover return value for variable in (v.group(0)", "references in kv/kvarrays that # are None. Would like to", "\"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The value", "== 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for", "OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module", "self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").') value =", "type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern", "elif variable_type == 'String': if embedded: value = self._read_embedded(value) #", "data provided for String.') elif variable_type == 'TCEntity': if validate", "proper structure for TC Entity.\"\"\" if data is None: return", "return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) return", "as e: self.log.error(e) return None def _create_array(self, key, value, validate=True):", "(#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat", "d in data: if not self._is_key_value(d): return False return True", "value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value =", "variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern +=", "for KeyValueArrays if data is not None: # pragma: no", "self._output_variables_by_name = None self._output_variables_by_type = None self.log = tcex.log #", "v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value =", "type replace the # quoted value to ensure the resulting", "False return True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON", "for var in set(variables): # recursion over set to handle", "}, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\":", "the correct instance only, handling the case where a variable", "'Binary': # if not isinstance(value, bytes): # value = value.encode('utf-8')", "from kv store # APP-1030 need to revisit this to", "no cover raise RuntimeError(f'Failed to serialize value ({e}).') try: return", "r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of String variable_pattern", "loadable JSON value = re.sub(f'\"{variable}\"', v, value) if v is", "def _variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\" return", "type self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").') value", "self._context = context self._output_variables = output_variables or [] # properties", "RuntimeError('Invalid data provided for String.') elif variable_type == 'TCEntity': if", "self.log.warning('The key or value field was None.') return data def", "True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided data has", "e: # pragma: no cover raise RuntimeError(f'Failed loading JSON data", "isinstance(value, bool): # coerce bool to str type self.log.warning(f'Coercing bool", "RuntimeError as e: self.log.error(e) return None def _create_array(self, key, value,", "'KeyValueArray': # embedded variable can be unquoted, which breaks JSON.", "or value is None: self.log.warning('The key or value field is", "cover raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def", "\"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args:", "tcex (TcEx): Instance of TcEx class. context (str): The Redis", "no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in", "if value is just the variable reference, # sub None", "value in Redis if applicable.\"\"\" if key is None or", "value def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. ..", "is not None: if validate and not isinstance(v, bytes): raise", "non-null value is returned from kv store # APP-1030 need", "for TC Entity Array.\"\"\" for d in data: if not", "r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property def _variable_array_types(self):", "decode: value = self._decode_binary(value) elif variable_type == 'KeyValue': # embedded", "not self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type", "def _is_tc_entity_array(self, data): \"\"\"Return True if provided data has proper", "\"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create method of", "kv store # APP-1030 need to revisit this to handle", "just the variable reference, # sub None value, else insert", "automatically covert variables embedded in a string with value retrieved", "validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.')", "the DB. value (bytes|int|string): The data to write to the", "determine data from redis originated as bytes or string. Args:", "for x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True", "to handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string", "output variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the", "= None if key is not None and value is", "@staticmethod def _load_value(value): \"\"\"Return the loaded JSON value or raise", "there are no keys/variables the raw string will be returned.", "\"embedded\" variables. .. Note:: The ``read()`` method will automatically determine", "Note:: The ``read()`` method will automatically determine if the input", "and b64decode: v = base64.b64decode(v) if decode: v = self._decode_binary(v)", "if data is None: return False return all(x in data", "try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma:", "d in data: if not self._is_tc_entity(d): return False return True", "as e: # pragma: no cover raise RuntimeError(f'Failed to serialize", "\"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided to", "] @property def _variable_single_types(self): \"\"\"Return list of standard playbook single", "the variable reference, # sub None value, else insert ''", "data @staticmethod def _is_key_value(data): \"\"\"Return True if provided data has", "self._is_tc_entity(d): return False return True @staticmethod def _load_value(value): \"\"\"Return the", "if validate and not isinstance(value, bytes): raise RuntimeError('Invalid data provided", "key field was None.') return value def parse_variable(self, variable): #", "\"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1:", "no cover variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data):", "isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.') value =", "Other data structures (dict, list, etc) must be serialized. Args:", "is None: # pragma: no cover self.log.warning('The null value for", "full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly", "_wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double quotes. Args:", "'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided data", "True if provided data has proper structure for Key Value.\"\"\"", "_read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. .. Note:: The", "array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray',", "\"\"\"Return True if provided data has proper structure for Key", "= self._load_value(value) elif variable_type == 'String': if embedded: value =", "will automatically covert variables embedded in a string with value", "False return all(x in data for x in ['key', 'value'])", "pragma: no cover return value for variable in (v.group(0) for", "return None def _create_array(self, key, value, validate=True): \"\"\"Create the value", "for Key Value.\"\"\" if data is None: return False return", "{self._context}, key: {key}, value: {value}') return value def _read_embedded(self, value):", "array is the wild-wild west, don't validate it if variable_type", "value) except RuntimeError as e: self.log.error(e) return None def _create_array(self,", "variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap", "key is None: self.log.warning('The key is None.') return None #", "of TcEx class. context (str): The Redis context (hash). output_variables", "pragma: no cover self.log.warning('The null value for key was provided.')", "@property def _variable_single_types(self): \"\"\"Return list of standard playbook single variable", "\"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context = context", "Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded", "# match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}')", "embedded variables. * Variables can only be embedded one level", "self._output_variables_by_type = {} for ov in self._output_variables: # parse the", "def variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder for", "[] for v in value: if v is not None:", "can't be loaded as JSON data. Returns: any: The de-serialized", "return False return all(x in data for x in ['id',", "values v = self._coerce_string_value(v) if validate and not isinstance(v, (type(None),", "value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError as e: self.log.error(e) return", "is None.') return None # get variable type from variable", "# pragma: no cover variables = [] for v in", "# APP-1030 need to revisit this to handle variable references", "parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded", "\"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables in", "has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\":", "variable rules: * Only user input can have embedded variables.", "}, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str):", "= tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') #", "return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded", "self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create", "return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard playbook", "key): \"\"\"Read method of CRUD operation for raw data. ..important::", "``read()`` method will automatically determine if the input is a", "requested output variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize", "isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided for", "x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if", "None if key is not None: value = self.tcex.key_value_store.read(self._context, key.strip())", "not None and b64decode: v = base64.b64decode(v) if decode: v", "to handle variable references in kv/kvarrays that # are None.", "says a bool is an int if isinstance(value, bool): #", "= self._load_value(value) if b64decode: value = base64.b64decode(value) if decode: value", "variables provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String']", "value is None: return value if variable_type == 'Binary': value", "data): \"\"\"Wrap keyvalue embedded variable in double quotes. Args: data", "in self._output_variables: # parse the variable to get individual parts", "non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching", "The requested output variables. \"\"\" def __init__(self, tcex, context, output_variables):", "{value}') try: value = json.dumps(value) except ValueError as e: #", "write to the DB. value (bytes|int|string): The data to write", "from DB \"\"\" # TODO: need to verify if core", "= r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of String", "west, don't validate it if variable_type != 'TCEnhancedEntityArray': if validate", "variable type from variable value variable_type = self.variable_type(key) try: value", "reference, # sub None value, else insert '' in string.", "if value is None: return value if variable_type == 'BinaryArray':", "= [ *value ] # spread the value so that", "# embedded variable can be unquoted, which breaks JSON. value", "if variable_type == 'BinaryArray': value_encoded = [] for v in", "variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning of", "variables. Returns: (str): Results retrieved from DB \"\"\" # TODO:", "value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.')", "a non-null value is returned from kv store # APP-1030", "create - context: {self._context}, key: {key}, value: {value}') return value", "in a string with value retrieved from DB. If there", "return all(x in data for x in ['id', 'value', 'type'])", "correct instance only, handling the case where a variable #", "coerce int to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing", "'TCEntity': if validate and (not isinstance(value, dict) or not self._is_tc_entity(value)):", "The data from key/value store. Raises: RuntimeError: Raise error when", "variable_type == 'BinaryArray': value_encoded = [] for v in value:", "elif variable_type == 'KeyValue': # embedded variable can be unquoted,", "method will automatically determine if the input is a variable", "validate and (not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid", "value.encode('utf-8') if validate and not isinstance(value, bytes): raise RuntimeError('Invalid data", "nested dict/list type replace the # quoted value to ensure", "key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as", "value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma:", "_variable_pattern(self): \"\"\"Regex pattern to match and parse a playbook variable.\"\"\"", "an upstream java App data = data.decode('latin-1') return data @staticmethod", "from key/value store. Raises: RuntimeError: Raise error when data can't", "v is not None and b64decode: v = base64.b64decode(v) if", "v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v,", "@property def _variable_array_types(self): \"\"\"Return list of standard playbook array variable", "properties.\"\"\" self.tcex = tcex self._context = context self._output_variables = output_variables", "\"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The value to", "variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray'", "of standard playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray',", "is None: return value if variable_type == 'Binary': value =", "The variable to write to the DB. value (bytes|int|string): The", "self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the", "= [] for v in value: if v is not", "to replace the correct instance only, handling the case where", "if not isinstance(value, bytes): # value = value.encode('utf-8') if validate", "value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray': if validate", "return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if", "data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type ==", "def _decode_binary(data): \"\"\"Return decoded bytes data handling data written by", "sends improper JSON for KeyValueArrays if data is not None:", "variable_type == 'KeyValue': if validate and (not isinstance(value, dict) or", "# self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}')", "#App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input:", "as e: self.log.error(e) return None if value is None: return", "key was provided.') return None # get variable type from", "variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity'", "and updated from the DB. Returns: (str): Results retrieved from", "for x in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return", "not isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.') #", "data provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced =", "of CRUD operation for raw data. ..important:: Raw data can", "# coerce int to str type if isinstance(value, (float, int)):", "times in the same key value array. data = data.replace(var,", "and not isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.')", "for embedded variables. Embedded variable rules: * Only user input", "determine if the input is a variable or needs to", "None: return value if variable_type == 'BinaryArray': value = json.loads(value,", "= base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value =", "= [] for v in self._load_value(value): # coerce string values", "value = self._coerce_string_value(value) if validate and not isinstance(value, str): raise", "a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger)", "has proper structure for Key Value Array.\"\"\" for d in", "the value in Redis if applicable.\"\"\" if key is None:", "Returns: (str): Result of DB write. \"\"\" data = None", "# standard library import base64 import json import re from", "Redis if applicable.\"\"\" if key is None or value is", "\"\"\"Return list of standard playbook single variable types.\"\"\" return [", "'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return list of standard", "be searched for embedded variables. Embedded variable rules: * Only", "Playbook Module Base Class Args: tcex (TcEx): Instance of TcEx", "= self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value =", "self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb create", "be embedded one level deep. This method will automatically covert", "True @staticmethod def _load_value(value): \"\"\"Return the loaded JSON value or", "class') def variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder", "if applicable.\"\"\" if key is None: # pragma: no cover", "retrieved from DB \"\"\" if value is None: # pragma:", "'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for v", "originated as bytes or string. Args: key (str): The variable", "for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key: {key},", "App data = data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return", "RuntimeError('Invalid data provided for Binary.') # if not isinstance(v, bytes):", "(str): The Redis context (hash). output_variables (list): The requested output", "in value: if v is not None: if validate and", "self._coerce_string_value(v) if validate and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid", "KeyValueArray with nested dict/list type replace the # quoted value", "a bool is an int if isinstance(value, bool): # coerce", "value = value_encoded elif variable_type == 'KeyValueArray': if validate and", "'KeyValue': if validate and (not isinstance(value, dict) or not self._is_key_value(value)):", "would require a kv-specific # version of this method that", "self._load_value(value) if b64decode: value = base64.b64decode(value) if decode: value =", "rules: * Only user input can have embedded variables. *", "v in value: if v is not None: if validate", "(hash). output_variables (list): The requested output variables. \"\"\" def __init__(self,", "returned a as string as there is no way to", "keys/variables the raw string will be returned. Examples:: DB Values", "The data with embedded variables. Returns: (str): Results retrieved from", "at beginning of String variable_pattern += r':([\\d]+)' # app id", "to write to the DB. Returns: (str): Result of DB", "and (not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid", "#App:7979:variable_name!String }] Args: value (str): The value to parsed and", "# variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type", "str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if", "or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') #", "\"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String", "value is None: return value if variable_type == 'BinaryArray': value", "of String variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern", "to be able to say if value is just the", "method that gets the entire list/dict instead of just the", "value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value = self._load_value(value)", "pragma: no cover raise RuntimeError(f'Failed to JSON load data \"{value}\"", "key.strip(), value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The key", "string value from an bool or int.\"\"\" # coerce bool", "'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of", "standard playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String',", "in Redis if applicable.\"\"\" if key is None: self.log.warning('The key", "self._coerce_string_value(value) if validate and not isinstance(value, str): raise RuntimeError('Invalid data", "if provided data has proper structure for TC Entity Array.\"\"\"", "no cover # for data written an upstream java App", "Base Class Args: tcex (TcEx): Instance of TcEx class. context", "be loaded as JSON data. Returns: any: The de-serialized value", "parsed_variable.get('type') # store the variables in dict by name (e.g.", "# for KeyValueArray with nested dict/list type replace the #", "embedded in a string with value retrieved from DB. If", "variables. \"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class", "The variable to read from the DB. Returns: (str): Results", "Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {}", "None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as", "variable type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list", "bool value ({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower()", "{self._context}, key: {key}, value: {value}') try: value = json.dumps(value) except", "embedded multiple times in the same key value array. data", "value field was None.') return data def read_raw(self, key): \"\"\"Read", "will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String:", "case where a variable # is embedded multiple times in", "create_raw(self, key, value): \"\"\"Create method of CRUD operation for raw", "self.log.warning('The key field was None.') return value def parse_variable(self, variable):", "by java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: #", "value field is None.') return None # get variable type", "is not None and b64decode: v = base64.b64decode(v) if decode:", "if provided data has proper structure for Key Value Array.\"\"\"", "key, value): \"\"\"Create method of CRUD operation for raw data.", "StringArray.') value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray': if", "Would like to be able to say if value is", "== 'String': if embedded: value = self._read_embedded(value) # coerce string", "@staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling data written", "to parsed and updated from the DB. Returns: (str): Results", "# variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type", "str(value).lower() # coerce int to str type if isinstance(value, (float,", "variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard playbook array", "= value.encode('utf-8') if validate and not isinstance(value, bytes): raise RuntimeError('Invalid", "are no keys/variables the raw string will be returned. Examples::", "= re.sub(variable, v, value) return value @property def _variable_pattern(self): \"\"\"Regex", "values value = self._coerce_string_value(value) if validate and not isinstance(value, str):", "value): \"\"\"Read method for \"embedded\" variables. .. Note:: The ``read()``", "variable_type == 'Binary': # if not isinstance(value, bytes): # value", "(str): The data with embedded variables. Returns: (str): Results retrieved", "data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create", "proper structure for Key Value Array.\"\"\" for d in data:", "DB \"\"\" # TODO: need to verify if core still", "_variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\" return self._variable_single_types", "variable to write to the DB. value (bytes|int|string): The data", "embedded=True): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\"", "spread the value so that we know it's a list", "value or raise an error. Args: value (str): The data", "TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key: {key}, value:", "child class') def variable_type(self, variable): # pragma: no cover \"\"\"Set", "int to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int", "elif variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise", "from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base", "self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable)", "# pragma: no cover raise RuntimeError(f'Failed loading JSON data ({value}).", "type from variable value variable_type = self.variable_type(key) # Enhanced entity", "for key was provided.') return None # get variable type", "not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb", "the variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] =", "variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom", "structure for Key Value.\"\"\" if data is None: return False", "None # get variable type from variable value variable_type =", "_parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook Class. **Example", "for child method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self,", "in ['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if", "level deep. This method will automatically covert variables embedded in", "'#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for ov", "(array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)'", "* Only String and KeyValueArray variables can have embedded variables.", "variable type from variable value variable_type = self.variable_type(key) # Enhanced", "or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.')", "DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\",", "if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value ({value}) to a", "DB. If there are no keys/variables the raw string will", "\"\"\"Return a string value from an bool or int.\"\"\" #", "json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in value: if", "if key is not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else:", "= re.sub(f'\"{variable}\"', v, value) if v is not None: #", "= self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) else:", "string values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity': value", "CRUD operation for raw data. ..important:: Bytes input will be", "_variable_single_types(self): \"\"\"Return list of standard playbook single variable types.\"\"\" return", "== 'Binary': # if not isinstance(value, bytes): # value =", "data def create_raw(self, key, value): \"\"\"Create method of CRUD operation", "beginning of String variable_pattern += r':([\\d]+)' # app id (:7979)", "#App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, {", "value = values elif variable_type == 'KeyValueArray': # embedded variable", "data = None if key is not None and value", "variable_type == 'KeyValueArray': # embedded variable can be unquoted, which", "({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce", "provided data has proper structure for Key Value.\"\"\" if data", "= self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as", "RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse", "..important:: Raw data can only be a byte, str or", "!= 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or isinstance(value,", "where a variable # is embedded multiple times in the", "data is loadable JSON value = re.sub(f'\"{variable}\"', v, value) if", "That would require a kv-specific # version of this method", "return value if variable_type == 'Binary': value = self._load_value(value) if", "from DB \"\"\" if value is None: # pragma: no", "provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue':", "elif variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value): raise", "object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover raise", "r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable", "# properties self._output_variables_by_name = None self._output_variables_by_type = None self.log =", "custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern", "\"\"\"Create the value in Redis if applicable.\"\"\" if key is", "def _variable_single_types(self): \"\"\"Return list of standard playbook single variable types.\"\"\"", "only replace variable if a non-null value is returned from", "'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of standard playbook", "data has proper structure for Key Value.\"\"\" if data is", "variable_type == 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid", "is None: return False return all(x in data for x", "\"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True, b64decode=True,", "method of CRUD operation for raw data. ..important:: Bytes input", "self._read_embedded(value) # coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type", "Bytes input will be returned a as string as there", "not self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return", "data written an upstream java App data = data.decode('latin-1') return", "and (not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data", "None or value is None: self.log.warning('The key or value field", "variables can have embedded variables. * Variables can only be", "raise RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(),", "variable_type = self.variable_type(key) try: value = self.tcex.key_value_store.read(self._context, key.strip()) except RuntimeError", "v = base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value", "have embedded variables. * Only String and KeyValueArray variables can", "data can only be a byte, str or int. Other", "value to ensure the resulting data is loadable JSON value", "= {'variable': ov} # store the variables in dict by", "== 'BinaryArray': value_encoded = [] for v in value: if", "_is_key_value(data): \"\"\"Return True if provided data has proper structure for", "playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data):", "\"key\": \"embedded string\", \"value\": \"This input has a embedded #App:7979:variable_name!String\"", "an error. Args: value (str): The data from key/value store.", "[] for v in self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v))", "variable_type == 'StringArray': if embedded: value = self._read_embedded(value) # convert", "\"\"\"Read method for \"embedded\" variables. .. Note:: The ``read()`` method", "e: self.log.error(e) return None if value is None: return value", "types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property", "self._read_embedded(value) # convert int to str value_coerced = [] for", "child method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self, key,", "store the variables in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}']", "coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type == 'TCEntity':", "= {} self._output_variables_by_type = {} for ov in self._output_variables: #", "variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' #", "(custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of standard", "(str): Result of DB write. \"\"\" data = None if", "input can have embedded variables. * Only String and KeyValueArray", "to determine data from redis originated as bytes or string.", "provided data has proper structure for Key Value Array.\"\"\" for", "string. Args: key (str): The variable to read from the", "if key is None: # pragma: no cover self.log.warning('The null", "== 'TCEntity': if validate and (not isinstance(value, dict) or not", "raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type == 'String':", "list of standard playbook single variable types.\"\"\" return [ 'Binary',", "..important:: Bytes input will be returned a as string as", "variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at beginning", "proper structure for TC Entity Array.\"\"\" for d in data:", "self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True", "method.\"\"\" raise NotImplementedError('Implemented in child class') def variable_type(self, variable): #", "method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self, key, array=False,", "must be serialized. Args: key (str): The variable to write", "f'\": \"{variable_string}\"') return data def create_raw(self, key, value): \"\"\"Create method", "String and KeyValueArray variables can have embedded variables. * Variables", "data = data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key,", "to a string (\"{str(value)}\").') value = str(value) return value def", "embedded variable can be unquoted, which breaks JSON. value =", "\"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx): Instance of", "the # quoted value to ensure the resulting data is", "json.dumps(value) except ValueError as e: # pragma: no cover raise", "have embedded variables. * Variables can only be embedded one", "variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ]", "output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context =", "[\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\": \"embedded string\",", "return False return all(x in data for x in ['key',", "None def _create_array(self, key, value, validate=True): \"\"\"Create the value in", "\"\"\"Return True if provided data has proper structure for TC", "var).group(0) # reformat to replace the correct instance only, handling", "# are None. Would like to be able to say", "\"three\"] Examples 3: Input: [{ \"key\": \"embedded string\", \"value\": \"This", "for KeyValue.') elif variable_type == 'String': # coerce string values", "byte, str or int. Other data structures (dict, list, etc)", "bytes or string. Args: key (str): The variable to read", "for v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable:", "+= r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property def", "revisit this to handle variable references in kv/kvarrays that #", "Key Value Array.\"\"\" for d in data: if not self._is_key_value(d):", "None: if validate and not isinstance(v, bytes): raise RuntimeError('Invalid data", "Args: key (str): The variable to write to the DB.", "\"\"\"Return list of standard playbook variable typesd.\"\"\" return self._variable_single_types +", "variable: {variable}, value: {v}') if isinstance(v, (dict, list)): v =", "variables = [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for", "= [] for v in value: # coerce string values", "get variable type from variable value variable_type = self.variable_type(key) if", "JSON for KeyValueArrays if data is not None: # pragma:", "try: data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e:", "of standard playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue',", "it if variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value,", "data. Returns: any: The de-serialized value from the key/value store.", "e: # pragma: no cover raise RuntimeError(f'Failed to serialize value", "({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e:", "bytes): # value = value.encode('utf-8') if validate and not isinstance(value,", "is None or value is None: self.log.warning('The key or value", "verify if core still sends improper JSON for KeyValueArrays if", "pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented", "class. context (str): The Redis context (hash). output_variables (list): The", "re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}')", "\"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class')", "(:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern +=", "recursion over set to handle duplicates # pull (#App:1441:embedded_string!String) from", "for raw data. ..important:: Bytes input will be returned a", "embedded one level deep. This method will automatically covert variables", "re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable) self._variable_parse =", "def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex", "None value, else insert '' in string. That would require", "return value def _create(self, key, value, validate=True): \"\"\"Create the value", "of this method that gets the entire list/dict instead of", "value = None if key is not None: value =", "list of standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types", "don't validate it if variable_type != 'TCEnhancedEntityArray': if validate and", "from redis originated as bytes or string. Args: key (str):", "self.log.trace(f'pb create - context: {self._context}, key: {key}, value: {value}') return", "matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for", "core still sends improper JSON for KeyValueArrays if data is", "= self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.') return", "dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value = [", "(e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True,", "= json.dumps(value) except ValueError as e: # pragma: no cover", "== 'KeyValue': if validate and (not isinstance(value, dict) or not", "variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array)", "for Binary.') # if not isinstance(v, bytes): # v =", "bool or int.\"\"\" # coerce bool before int as python", "be returned a as string as there is no way", "v is not None: # only replace variable if a", "isinstance(v, (dict, list)): v = json.dumps(v) # for KeyValueArray with", "#App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace the", "**Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type", "key/value store. Raises: RuntimeError: Raise error when data can't be", "Results retrieved from DB. \"\"\" value = None if key", "data. ..important:: Raw data can only be a byte, str", "self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was None.') return value", "data can't be loaded as JSON data. Returns: any: The", "RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value = value_coerced elif", "variable to read from the DB. Returns: (str): Results retrieved", "value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value)", "get variable type from variable value variable_type = self.variable_type(key) #", "method for \"embedded\" variables. .. Note:: The ``read()`` method will", "['id', 'value', 'type']) def _is_tc_entity_array(self, data): \"\"\"Return True if provided", "json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no cover", "in data for x in ['key', 'value']) def _is_key_value_array(self, data):", "elif variable_type == 'StringArray': if embedded: value = self._read_embedded(value) #", "2: Input: [\"one\", #App:7979:two!String, \"three\"] Examples 3: Input: [{ \"key\":", "(:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern +=", "applicable.\"\"\" if key is None: self.log.warning('The key is None.') return", "variable if a non-null value is returned from kv store", "# variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for", "variable_type(self, variable): # pragma: no cover \"\"\"Set placeholder for child", "{variable_type}.') value = [ *value ] # spread the value", "value: {v}') if isinstance(v, (dict, list)): v = json.dumps(v) #", "from the DB. Returns: (str): Results retrieved from DB. \"\"\"", "value if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values", "int as python says a bool is an int if", "# store the variables in dict by name-type (e.g. \"status_code-String\")", "self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) value = self._load_value(value) elif", "RuntimeError('Invalid data provided for Binary.') value = base64.b64encode(value).decode('utf-8') elif variable_type", "(dict, list, etc) must be serialized. Args: key (str): The", "isinstance(value, Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided", "Args: value (str): The value to parsed and updated from", "elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) #", "be a byte, str or int. Other data structures (dict,", "RuntimeError as e: self.log.error(e) return None if value is None:", "DB. \"\"\" value = None if key is not None:", "embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray },", "for child method.\"\"\" raise NotImplementedError('Implemented in child class') def read(self,", "if variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable)", "in Redis if applicable.\"\"\" if key is None: # pragma:", "data provided for TcEntity.') # self.log.trace(f'pb create - context: {self._context},", "isinstance(value, bytes): # value = value.encode('utf-8') if validate and not", "RuntimeError('Invalid data provided for KeyValue.') elif variable_type == 'String': #", "e: self.log.error(e) return None def _create_array(self, key, value, validate=True): \"\"\"Create", "ov} # store the variables in dict by name-type (e.g.", "validate and (not isinstance(value, Iterable) or isinstance(value, (str, dict))): raise", "data with embedded variables. Returns: (str): Results retrieved from DB", "None: # pragma: no cover return value for variable in", "is loadable JSON value = re.sub(f'\"{variable}\"', v, value) if v", "variable type (array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array)", "written an upstream java App data = data.decode('latin-1') return data", "written by java apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError:", "embedded variables. Returns: (str): Results retrieved from DB \"\"\" #", "an int if isinstance(value, bool): # coerce bool to str", "# coerce bool before int as python says a bool", "pragma: no cover raise RuntimeError(f'Failed loading JSON data ({value}). Error:", "ValueError as e: # pragma: no cover raise RuntimeError(f'Failed to", "# pragma: no cover self.log.warning('The null value for key was", "RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif variable_type ==", "a string (\"{str(value)}\").') value = str(value) return value def _create(self,", "for {variable_type}.') value = [ *value ] # spread the", "was None.') return value def parse_variable(self, variable): # pragma: no", "applicable.\"\"\" if key is None or value is None: self.log.warning('The", "if value is None: # pragma: no cover return value", "to read from the DB. Returns: (str): Results retrieved from", "raw data. ..important:: Raw data can only be a byte,", "raw string will be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded", "to match and parse a playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)'", "from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to", "no way to determine data from redis originated as bytes", "value: # coerce string values v = self._coerce_string_value(v) if validate", "is not None and value is not None: try: data", "or string. Args: key (str): The variable to read from", "apps.\"\"\" try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no", "Raises: RuntimeError: Raise error when data can't be loaded as", "Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"]", "else: self.log.warning('The key or value field was None.') return data", "read(self, key, array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder", "value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value", "data has proper structure for Key Value Array.\"\"\" for d", "value if variable_type == 'Binary': value = self._load_value(value) if b64decode:", "_read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis", "(as opposed to an iterable) if variable_type == 'BinaryArray': value_encoded", "replace variable if a non-null value is returned from kv", "self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key: {key}, value:", "import re from collections import OrderedDict from collections.abc import Iterable", "value for key was provided.') return None # get variable", "get individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type", "if decode: v = self._decode_binary(v) values.append(v) value = values elif", "in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables): # recursion", "no cover return value for variable in (v.group(0) for v", "Examples 3: Input: [{ \"key\": \"embedded string\", \"value\": \"This input", "if applicable.\"\"\" if key is None: self.log.warning('The key is None.')", "= re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value from", "to str value_coerced = [] for v in self._load_value(value): #", "tcex self._context = context self._output_variables = output_variables or [] #", "# coerce string values v = self._coerce_string_value(v) if validate and", "== 'KeyValueArray': # embedded variable can be unquoted, which breaks", "from collections import OrderedDict from collections.abc import Iterable class PlaybooksBase:", "the variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] =", "bool to str type self.log.warning(f'Coercing bool value ({value}) to a", "if data is not None: # pragma: no cover variables", "load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables", "variable_pattern += r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)'", "variable # is embedded multiple times in the same key", "\"\"\" # TODO: need to verify if core still sends", "DB write. \"\"\" data = None if key is not", "or int.\"\"\" # coerce bool before int as python says", "Array.\"\"\" for d in data: if not self._is_key_value(d): return False", "validate and (not isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid", "read_raw(self, key): \"\"\"Read method of CRUD operation for raw data.", "self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable can be", "type from variable value variable_type = self.variable_type(key) try: value =", "{value}') return value def _read_embedded(self, value): \"\"\"Read method for \"embedded\"", "self._output_variables = output_variables or [] # properties self._output_variables_by_name = None", "validate and not isinstance(value, str): raise RuntimeError('Invalid data provided for", "value = self._load_value(value) # self.log.trace(f'pb create - context: {self._context}, key:", "variable): # pragma: no cover \"\"\"Set placeholder for child method.\"\"\"", "variable type from variable value variable_type = self.variable_type(key) if variable_type", "validate it if variable_type != 'TCEnhancedEntityArray': if validate and (not", "deep. This method will automatically covert variables embedded in a", "dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def", "self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict, list)): v", "keyvalue embedded variable in double quotes. Args: data (str): The", "for d in data: if not self._is_key_value(d): return False return", "playbook single variable types.\"\"\" return [ 'Binary', 'KeyValue', 'String', 'TCEntity',", "\"This input has a embedded #App:7979:variable_name!String\" }, { \"key\": \"string", "or value field was None.') return data def read_raw(self, key):", "self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e) else: self.log.warning('The", "self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable in double", "as e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded", "data): \"\"\"Return True if provided data has proper structure for", "def _is_key_value_array(self, data): \"\"\"Return True if provided data has proper", "_is_key_value_array(self, data): \"\"\"Return True if provided data has proper structure", "str(value) return value def _create(self, key, value, validate=True): \"\"\"Create the", "'' in string. That would require a kv-specific # version", "data from key/value store. Raises: RuntimeError: Raise error when data", "and not isinstance(value, str): raise RuntimeError('Invalid data provided for String.')", "Class Args: tcex (TcEx): Instance of TcEx class. context (str):", "list)): v = json.dumps(v) # for KeyValueArray with nested dict/list", "== 'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data", "context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex self._context", "\"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\":", "key, array=False, embedded=True): # pragma: no cover \"\"\"Set placeholder for", "\"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: #", "input has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\", #App:7979:two!String,", "v in re.finditer(self._variable_parse, str(value))): v = self.read(variable) self.log.trace(f'embedded variable: {variable},", "in dict by name-type (e.g. \"status_code-String\") self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov}", "variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables", "for StringArray.') value_coerced.append(v) value = value_coerced elif variable_type == 'TCEntityArray':", "is None: self.log.warning('The key is None.') return None # get", "'KeyValue': # embedded variable can be unquoted, which breaks JSON.", "['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return True if provided data", "\"value\": #App:7979:variable_name!String }] Args: value (str): The value to parsed", "to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the", "return data def read_raw(self, key): \"\"\"Read method of CRUD operation", "v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded elif variable_type ==", "base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type == 'KeyValue':", "self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String': if embedded:", "covert variables embedded in a string with value retrieved from", "id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern", "as there is no way to determine data from redis", "value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value", "is a variable or needs to be searched for embedded", "{'variable': ov} # store the variables in dict by name-type", "if embedded: value = self._read_embedded(value) value = self._load_value(value) elif variable_type", "== 'StringArray': if embedded: value = self._read_embedded(value) # convert int", "to get individual parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name')", "# pragma: no cover raise RuntimeError(f'Failed to JSON load data", "\"\"\" value = None if key is not None: value", "self.variable_type(key) # Enhanced entity array is the wild-wild west, don't", "loading JSON data ({value}). Error: ({e})') elif variable_type == 'StringArray':", "var in set(variables): # recursion over set to handle duplicates", "# if not isinstance(value, bytes): # value = value.encode('utf-8') if", "able to say if value is just the variable reference,", "not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type", "variable_type = self.variable_type(key) # Enhanced entity array is the wild-wild", "if variable_type == 'Binary': value = self._load_value(value) if b64decode: value", "'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self): \"\"\"Return", "value from the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict)", "can only be embedded one level deep. This method will", "isinstance(v, bytes): raise RuntimeError('Invalid data provided for Binary.') # if", "str type self.log.warning(f'Coercing bool value ({value}) to a string (\"{str(value).lower()}\").')", "only be embedded one level deep. This method will automatically", "# Enhanced entity array is the wild-wild west, don't validate", "Returns: (str): Results retrieved from DB. \"\"\" value = None", "value) except RuntimeError as e: self.log.error(e) return None @staticmethod def", "value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']:", "self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data", "#App:7979:variable_name!StringArray }, { \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value", "as e: # pragma: no cover raise RuntimeError(f'Failed loading JSON", "return all(x in data for x in ['key', 'value']) def", "not None: # only replace variable if a non-null value", "+= r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))'", "replace the # quoted value to ensure the resulting data", "1: Input: \"This input has a embedded #App:7979:variable_name!String\" Examples 2:", "{v}') if isinstance(v, (dict, list)): v = json.dumps(v) # for", "data handling data written by java apps.\"\"\" try: data =", "standard library import base64 import json import re from collections", "is None: # pragma: no cover return value for variable", "values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity',", "store the variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name]", "the entire list/dict instead of just the string. value =", "Raw data can only be a byte, str or int.", "# coerce string values value = self._coerce_string_value(value) if validate and", "retrieved from DB. \"\"\" value = None if key is", "variable_type == 'String': if embedded: value = self._read_embedded(value) # coerce", "cover \"\"\"Set placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child", "value = json.dumps(value) except ValueError as e: # pragma: no", "value = [ *value ] # spread the value so", "value is not None: try: data = self.tcex.key_value_store.create(self._context, key.strip(), value)", "iterable) if variable_type == 'BinaryArray': value_encoded = [] for v", "standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self,", "quotes. Args: data (str): The data with embedded variables. Returns:", "value_encoded = [] for v in value: if v is", "ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value", "string (\"{str(value)}\").') value = str(value) return value def _create(self, key,", "decoded bytes data handling data written by java apps.\"\"\" try:", "Embedded variable rules: * Only user input can have embedded", "= {'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create", "= value_coerced elif variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value =", "_variable_array_types(self): \"\"\"Return list of standard playbook array variable types.\"\"\" return", "variable type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern", "the DB. Returns: (str): Results retrieved from DB \"\"\" if", "not isinstance(value, bytes): raise RuntimeError('Invalid data provided for Binary.') value", "import base64 import json import re from collections import OrderedDict", "matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom)", "def _load_value(value): \"\"\"Return the loaded JSON value or raise an", "def _variable_array_types(self): \"\"\"Return list of standard playbook array variable types.\"\"\"", "from DB. \"\"\" value = None if key is not", "return value for variable in (v.group(0) for v in re.finditer(self._variable_parse,", "def create_raw(self, key, value): \"\"\"Create method of CRUD operation for", "+= r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' #", "key or value field was None.') return data def read_raw(self,", "bool is an int if isinstance(value, bool): # coerce bool", "def _read(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create the value in", "if key is not None and value is not None:", "handle duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string =", "Enhanced entity array is the wild-wild west, don't validate it", "== 'TCEntityArray': if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data", "a variable # is embedded multiple times in the same", "Results retrieved from DB \"\"\" if value is None: #", "base64.b64decode(v) if decode: v = self._decode_binary(v) values.append(v) value = values", "'String': # coerce string values value = self._coerce_string_value(value) if validate", "If there are no keys/variables the raw string will be", "[ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def _variable_single_types(self):", "module\"\"\" # standard library import base64 import json import re", "not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') # self.log.trace(f'pb", "with nested dict/list type replace the # quoted value to", "DB. value (bytes|int|string): The data to write to the DB.", "write to the DB. Returns: (str): Result of DB write.", "to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except", "NotImplementedError('Implemented in child class') def variable_type(self, variable): # pragma: no", "= [] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var", "variable_type = self.variable_type(key) if variable_type == 'Binary': # if not", "if not self._is_key_value(d): return False return True @staticmethod def _is_tc_entity(data):", "string. value = re.sub(variable, v, value) return value @property def", "standard playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray',", "isinstance(value, dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for", "v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value = value_encoded", "list, etc) must be serialized. Args: key (str): The variable", "not self._is_tc_entity(d): return False return True @staticmethod def _load_value(value): \"\"\"Return", "self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True, decode=False): \"\"\"Create", "None if key is not None and value is not", "if key is None: self.log.warning('The key is None.') return None", "variables. * Only String and KeyValueArray variables can have embedded", "data): variables.append(v.group(0)) for var in set(variables): # recursion over set", "which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value =", "v in value: # coerce string values v = self._coerce_string_value(v)", "v = json.dumps(v) # for KeyValueArray with nested dict/list type", "# if not isinstance(v, bytes): # v = v.encode('utf-8') v", "type from variable value variable_type = self.variable_type(key) if variable_type ==", "self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict, list)):", "KeyValue.') elif variable_type == 'String': # coerce string values value", "# pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0)", "{ \"key\": \"string\", \"value\": #App:7979:variable_name!String }] Args: value (str): The", "Only String and KeyValueArray variables can have embedded variables. *", "[{ \"key\": \"embedded string\", \"value\": \"This input has a embedded", "= self.read(variable) self.log.trace(f'embedded variable: {variable}, value: {v}') if isinstance(v, (dict,", "field was None.') return value def parse_variable(self, variable): # pragma:", "self._output_variables_by_name[variable_name] = {'variable': ov} # store the variables in dict", "cover raise RuntimeError(f'Failed loading JSON data ({value}). Error: ({e})') elif", "instance only, handling the case where a variable # is", "list (as opposed to an iterable) if variable_type == 'BinaryArray':", "raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value = value_coerced", "key is None: # pragma: no cover self.log.warning('The null value", "structure for TC Entity.\"\"\" if data is None: return False", "for v in value: if v is not None: if", "return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no", "was None.') return data def read_raw(self, key): \"\"\"Read method of", "key, value, validate=True): \"\"\"Create the value in Redis if applicable.\"\"\"", "from variable value variable_type = self.variable_type(key) # Enhanced entity array", "DB. Returns: (str): Results retrieved from DB \"\"\" if value", "without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return", "provided for {variable_type}.') value = [ *value ] # spread", "variables.append(v.group(0)) for var in set(variables): # recursion over set to", "key: {key}, value: {value}') try: value = json.dumps(value) except ValueError", "capture variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern) #", "Iterable) or isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for", "except ValueError as e: # pragma: no cover raise RuntimeError(f'Failed", "[] for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in", "if validate and (not isinstance(value, dict) or not self._is_key_value(value)): raise", "java App data = data.decode('latin-1') return data @staticmethod def _is_key_value(data):", "variable_type == 'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid", "self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in self._output_variables:", "from the DB. Returns: (str): Results retrieved from DB \"\"\"", "value, else insert '' in string. That would require a", "def read(self, key, array=False, embedded=True): # pragma: no cover \"\"\"Set", "\"This input has a embedded #App:7979:variable_name!String\" Examples 2: Input: [\"one\",", "key is None.') return None # get variable type from", "self.tcex = tcex self._context = context self._output_variables = output_variables or", "None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling data", "value is returned from kv store # APP-1030 need to", "== 'String': # coerce string values value = self._coerce_string_value(value) if", "None: # only replace variable if a non-null value is", "searched for embedded variables. Embedded variable rules: * Only user", "raise RuntimeError(f'Failed to JSON load data \"{value}\" ({e}).') def _parse_output_variables(self):", "raise RuntimeError('Invalid data provided for TcEntity.') # self.log.trace(f'pb create -", "child class') def read(self, key, array=False, embedded=True): # pragma: no", "quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a", "DB. Returns: (str): Result of DB write. \"\"\" data =", "str)): raise RuntimeError('Invalid data provided for StringArray.') value_coerced.append(v) value =", "= None self.log = tcex.log # match full variable self._variable_match", "self.log = tcex.log # match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$')", "JSON data ({value}). Error: ({e})') elif variable_type == 'StringArray': if", "_is_tc_entity_array(self, data): \"\"\"Return True if provided data has proper structure", "value = base64.b64decode(value) if decode: value = self._decode_binary(value) elif variable_type", "field was None.') return data def read_raw(self, key): \"\"\"Read method", "to an iterable) if variable_type == 'BinaryArray': value_encoded = []", "None: # pragma: no cover self.log.warning('The null value for key", "= self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String': if", "app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name)", "self._load_value(value): # coerce string values value_coerced.append(self._coerce_string_value(v)) value = value_coerced elif", "type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern", "# recursion over set to handle duplicates # pull (#App:1441:embedded_string!String)", "# for data written an upstream java App data =", "for TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key: {key},", "in string. That would require a kv-specific # version of", "input is a variable or needs to be searched for", "_create(self, key, value, validate=True): \"\"\"Create the value in Redis if", "entire list/dict instead of just the string. value = re.sub(variable,", "parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder for child", "cover # for data written an upstream java App data", "'TCEntity': value = self._load_value(value) return value def _read_array(self, key, embedded=True,", "value_coerced = [] for v in self._load_value(value): # coerce string", "there is no way to determine data from redis originated", "_decode_binary(data): \"\"\"Return decoded bytes data handling data written by java", "pattern to match and parse a playbook variable.\"\"\" variable_pattern =", "value is None: self.log.warning('The key or value field is None.')", "all(x in data for x in ['id', 'value', 'type']) def", "= None self._output_variables_by_type = None self.log = tcex.log # match", "value = base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and", "value from an bool or int.\"\"\" # coerce bool before", "variables embedded in a string with value retrieved from DB.", "str or int. Other data structures (dict, list, etc) must", "embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self,", "for d in data: if not self._is_tc_entity(d): return False return", "value = str(value).lower() # coerce int to str type if", "None if value is None: return value if variable_type ==", "context self._output_variables = output_variables or [] # properties self._output_variables_by_name =", "\"\"\"Parse the output variables provided to Playbook Class. **Example Variable", "None: # pragma: no cover variables = [] for v", "= value_coerced elif variable_type == 'TCEntityArray': if validate and not", "quoted value to ensure the resulting data is loadable JSON", "value_coerced = [] for v in value: # coerce string", "validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for KeyValueArray.')", "will automatically determine if the input is a variable or", "still sends improper JSON for KeyValueArrays if data is not", "Binary.') # if not isinstance(v, bytes): # v = v.encode('utf-8')", "The Redis context (hash). output_variables (list): The requested output variables.", "with value retrieved from DB. If there are no keys/variables", "if a non-null value is returned from kv store #", "be returned. Examples:: DB Values #App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\"", "'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list of standard", "the DB. Returns: (str): Result of DB write. \"\"\" data", "or value field is None.') return None # get variable", "error when data can't be loaded as JSON data. Returns:", "({value}). Error: ({e})') elif variable_type == 'StringArray': if embedded: value", "def _coerce_string_value(self, value): \"\"\"Return a string value from an bool", "a variable or needs to be searched for embedded variables.", "cover return value for variable in (v.group(0) for v in", "(list): The requested output variables. \"\"\" def __init__(self, tcex, context,", "({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided to Playbook", "data: if not self._is_key_value(d): return False return True @staticmethod def", "Input: [{ \"key\": \"embedded string\", \"value\": \"This input has a", "if v is not None: # only replace variable if", "parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type') #", "data for x in ['key', 'value']) def _is_key_value_array(self, data): \"\"\"Return", "type (custom) return variable_pattern @property def _variable_array_types(self): \"\"\"Return list of", "self._is_key_value(value)): raise RuntimeError('Invalid data provided for KeyValue.') elif variable_type ==", "the variable to get individual parts parsed_variable = self.parse_variable(ov) variable_name", "value = json.loads(value, object_pairs_hook=OrderedDict) values = [] for v in", "r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' #", "data from redis originated as bytes or string. Args: key", "Framework Playbook module\"\"\" # standard library import base64 import json", "RuntimeError: Raise error when data can't be loaded as JSON", "any: The de-serialized value from the key/value store. \"\"\" try:", "json import re from collections import OrderedDict from collections.abc import", "if key is None or value is None: self.log.warning('The key", "Args: data (str): The data with embedded variables. Returns: (str):", "* Variables can only be embedded one level deep. This", "variables in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable':", "match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def", "def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables. .. Note::", "need to revisit this to handle variable references in kv/kvarrays", "(str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value =", "(str): Results retrieved from DB \"\"\" if value is None:", "to verify if core still sends improper JSON for KeyValueArrays", "to write to the DB. value (bytes|int|string): The data to", "except UnicodeDecodeError: # pragma: no cover # for data written", "if embedded: value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict)", "in data: if not self._is_key_value(d): return False return True @staticmethod", "and KeyValueArray variables can have embedded variables. * Variables can", "(#App,#Trigger) at beginning of String variable_pattern += r':([\\d]+)' # app", "(#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string", "\"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for ov in", "context: {self._context}, key: {key}, value: {value}') try: value = json.dumps(value)", "JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try:", "value): \"\"\"Return a string value from an bool or int.\"\"\"", "PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex (TcEx): Instance", "as e: self.log.error(e) else: self.log.warning('The key or value field was", "not None: # pragma: no cover variables = [] for", "provided for KeyValue.') elif variable_type == 'String': # coerce string", "try: return self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e)", "no cover self.log.warning('The null value for key was provided.') return", "if v is not None: if validate and not isinstance(v,", "= output_variables or [] # properties self._output_variables_by_name = None self._output_variables_by_type", "\"value\": \"This input has a embedded #App:7979:variable_name!String\" }, { \"key\":", "isinstance(value, (str, dict))): raise RuntimeError(f'Invalid data provided for {variable_type}.') value", "in data for x in ['id', 'value', 'type']) def _is_tc_entity_array(self,", "Redis if applicable.\"\"\" if key is None: self.log.warning('The key is", "playbook array variable types.\"\"\" return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray',", "in double quotes. Args: data (str): The data with embedded", "re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value from an", "an bool or int.\"\"\" # coerce bool before int as", "validate and not isinstance(value, bytes): raise RuntimeError('Invalid data provided for", "as string as there is no way to determine data", "in child class') def variable_type(self, variable): # pragma: no cover", "] @property def _variable_types(self): \"\"\"Return list of standard playbook variable", "values.append(v) value = values elif variable_type == 'KeyValueArray': # embedded", "ValueError as e: # pragma: no cover raise RuntimeError(f'Failed loading", "#App:7979:variable_name!String: \"embedded \\\\\"variable\\\\\"\" #App:7979:two!String: \"two\" #App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples", "if provided data has proper structure for TC Entity.\"\"\" if", "(not isinstance(value, dict) or not self._is_key_value(value)): raise RuntimeError('Invalid data provided", "for KeyValueArray with nested dict/list type replace the # quoted", "that we know it's a list (as opposed to an", "try: data = data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover", "The value to parsed and updated from the DB. Returns:", "if decode: value = self._decode_binary(value) elif variable_type == 'KeyValue': #", "data written by java apps.\"\"\" try: data = data.decode('utf-8') except", "for Key Value Array.\"\"\" for d in data: if not", "raise RuntimeError('Invalid data provided for Binary.') # if not isinstance(v,", "# parse the variable to get individual parts parsed_variable =", "structures (dict, list, etc) must be serialized. Args: key (str):", "in Redis if applicable.\"\"\" if key is None or value", "key.strip()) except RuntimeError as e: self.log.error(e) return None if value", "return [ 'BinaryArray', 'KeyValueArray', 'StringArray', 'TCEntityArray', 'TCEnhancedEntityArray', ] @property def", "self._vars_keyvalue_embedded = re.compile(fr'(?:\\\"\\:\\s?)[^\\\"]?{self._variable_pattern}') def _coerce_string_value(self, value): \"\"\"Return a string value", "b64decode: value = base64.b64decode(value) if decode: value = self._decode_binary(value) elif", "= self._load_value(value) return value def _read_array(self, key, embedded=True, b64decode=True, decode=False):", "not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for StringArray.')", "is returned from kv store # APP-1030 need to revisit", "if v is not None and b64decode: v = base64.b64decode(v)", "variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom) return variable_pattern @property", "Key Value.\"\"\" if data is None: return False return all(x", "int if isinstance(value, bool): # coerce bool to str type", "variable_type == 'String': # coerce string values value = self._coerce_string_value(value)", "structure for Key Value Array.\"\"\" for d in data: if", "self._output_variables_by_type = None self.log = tcex.log # match full variable", "for ov in self._output_variables: # parse the variable to get", "KeyValueArrays if data is not None: # pragma: no cover", "as e: # pragma: no cover raise RuntimeError(f'Failed to JSON", "import OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx Playbook", "self._decode_binary(v) values.append(v) value = values elif variable_type == 'KeyValueArray': #", "@property def _variable_types(self): \"\"\"Return list of standard playbook variable typesd.\"\"\"", "== 'StringArray': value_coerced = [] for v in value: #", "def _create(self, key, value, validate=True): \"\"\"Create the value in Redis", "# convert int to str value_coerced = [] for v", "a string value from an bool or int.\"\"\" # coerce", "elif variable_type == 'TCEntity': if validate and (not isinstance(value, dict)", "say if value is just the variable reference, # sub", "if validate and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for", "parts parsed_variable = self.parse_variable(ov) variable_name = parsed_variable.get('name') variable_type = parsed_variable.get('type')", "raise an error. Args: value (str): The data from key/value", "variable_type == 'KeyValue': # embedded variable can be unquoted, which", "decode: v = self._decode_binary(v) values.append(v) value = values elif variable_type", "context (hash). output_variables (list): The requested output variables. \"\"\" def", "base64.b64encode(value).decode('utf-8') elif variable_type == 'KeyValue': if validate and (not isinstance(value,", "python says a bool is an int if isinstance(value, bool):", "self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e:", "'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create - context:", "None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field was", "by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov} # store", "value array. data = data.replace(var, f'\": \"{variable_string}\"') return data def", "return data def create_raw(self, key, value): \"\"\"Create method of CRUD", "# get variable type from variable value variable_type = self.variable_type(key)", "decode=False): \"\"\"Create the value in Redis if applicable.\"\"\" if key", "_coerce_string_value(self, value): \"\"\"Return a string value from an bool or", "# v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value =", "value = self._decode_binary(value) elif variable_type == 'KeyValue': # embedded variable", "(str): The value to parsed and updated from the DB.", "def _variable_pattern(self): \"\"\"Regex pattern to match and parse a playbook", "# pragma: no cover \"\"\"Set placeholder for child method.\"\"\" raise", "embedded: value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except", "the key/value store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError", "Args: tcex (TcEx): Instance of TcEx class. context (str): The", "in value: if v is not None and b64decode: v", "\"\"\" def __init__(self, tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\"", "ensure the resulting data is loadable JSON value = re.sub(f'\"{variable}\"',", "variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a", "value: {value}') try: value = json.dumps(value) except ValueError as e:", "# variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type", "if the input is a variable or needs to be", "data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output variables provided", "tcex, context, output_variables): \"\"\"Initialize the Class properties.\"\"\" self.tcex = tcex", "will be returned a as string as there is no", "as bytes or string. Args: key (str): The variable to", "in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb create", "re.compile(self._variable_pattern) # match embedded variables without quotes (#App:7979:variable_name!StringArray) self._vars_keyvalue_embedded =", "= self._decode_binary(v) values.append(v) value = values elif variable_type == 'KeyValueArray':", "def read_raw(self, key): \"\"\"Read method of CRUD operation for raw", "raise RuntimeError(f'Invalid data provided for {variable_type}.') value = [ *value", "raise RuntimeError('Invalid data provided for KeyValueArray.') elif variable_type == 'StringArray':", "to str type if isinstance(value, (float, int)): self.log.warning(f'Coercing float/int value", "None: return False return all(x in data for x in", "= None if key is not None: value = self.tcex.key_value_store.read(self._context,", "value = value.encode('utf-8') if validate and not isinstance(value, bytes): raise", "parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables in dict", "and not self._is_tc_entity_array(value): raise RuntimeError('Invalid data provided for TcEntityArray.') #", "# quoted value to ensure the resulting data is loadable", "TcEx class. context (str): The Redis context (hash). output_variables (list):", "was provided.') return None # get variable type from variable", "value ({value}) to a string (\"{str(value)}\").') value = str(value) return", "embedded=True, b64decode=True, decode=False): \"\"\"Create the value in Redis if applicable.\"\"\"", "if embedded: value = self._read_embedded(value) # convert int to str", "one level deep. This method will automatically covert variables embedded", "Returns: (str): Results retrieved from DB \"\"\" if value is", "if validate and (not isinstance(value, Iterable) or isinstance(value, (str, dict))):", "string as there is no way to determine data from", "all(x in data for x in ['key', 'value']) def _is_key_value_array(self,", "data provided for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context},", "e: # pragma: no cover raise RuntimeError(f'Failed to JSON load", "is None: return value if variable_type == 'BinaryArray': value =", "= data.replace(var, f'\": \"{variable_string}\"') return data def create_raw(self, key, value):", "NotImplementedError('Implemented in child class') def read(self, key, array=False, embedded=True): #", "or raise an error. Args: value (str): The data from", "Results retrieved from DB \"\"\" # TODO: need to verify", "collections import OrderedDict from collections.abc import Iterable class PlaybooksBase: \"\"\"TcEx", "in child class') def read(self, key, array=False, embedded=True): # pragma:", "TC Entity.\"\"\" if data is None: return False return all(x", "data.decode('utf-8') except UnicodeDecodeError: # pragma: no cover # for data", "return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes data handling", "value) if v is not None: # only replace variable", "variable_type != 'TCEnhancedEntityArray': if validate and (not isinstance(value, Iterable) or", "of standard playbook variable typesd.\"\"\" return self._variable_single_types + self._variable_array_types def", "# match full variable self._variable_match = re.compile(fr'^{self._variable_pattern}$') # capture variable", "variables. Embedded variable rules: * Only user input can have", "+= r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non", "placeholder for child method.\"\"\" raise NotImplementedError('Implemented in child class') def", "data has proper structure for TC Entity.\"\"\" if data is", "'KeyValueArray': if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided", "the value in Redis if applicable.\"\"\" if key is None", "return value def _read_embedded(self, value): \"\"\"Read method for \"embedded\" variables.", "list of standard playbook array variable types.\"\"\" return [ 'BinaryArray',", "string values value = self._coerce_string_value(value) if validate and not isinstance(value,", "cover raise RuntimeError(f'Failed to serialize value ({e}).') try: return self.tcex.key_value_store.create(self._context,", "pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) #", "key or value field is None.') return None # get", "JSON value = re.sub(f'\"{variable}\"', v, value) if v is not", "validate and not isinstance(v, bytes): raise RuntimeError('Invalid data provided for", "embedded: value = self._read_embedded(value) # coerce string values value =", "data ({value}). Error: ({e})') elif variable_type == 'StringArray': if embedded:", "kv/kvarrays that # are None. Would like to be able", "'StringArray': value_coerced = [] for v in value: # coerce", "in data: if not self._is_tc_entity(d): return False return True @staticmethod", "the raw string will be returned. Examples:: DB Values #App:7979:variable_name!String:", "variable reference, # sub None value, else insert '' in", "value = self._read_embedded(value) # convert int to str value_coerced =", "elif variable_type == 'String': # coerce string values value =", "# coerce string values value = self._coerce_string_value(self._load_value(value)) elif variable_type ==", "\"\"\"Regex pattern to match and parse a playbook variable.\"\"\" variable_pattern", "# store the variables in dict by name (e.g. \"status_code\")", "value = self._read_embedded(value) value = self._load_value(value) elif variable_type == 'String':", "the same key value array. data = data.replace(var, f'\": \"{variable_string}\"')", "variable or needs to be searched for embedded variables. Embedded", "to ensure the resulting data is loadable JSON value =", "kv-specific # version of this method that gets the entire", "in dict by name (e.g. \"status_code\") self._output_variables_by_name[variable_name] = {'variable': ov}", "# pragma: no cover raise RuntimeError(f'Failed to serialize value ({e}).')", "the value so that we know it's a list (as", "value = self._wrap_embedded_keyvalue(value) if embedded: value = self._read_embedded(value) try: value", "for v in re.finditer(self._vars_keyvalue_embedded, data): variables.append(v.group(0)) for var in set(variables):", "key (str): The variable to write to the DB. value", "value @property def _variable_pattern(self): \"\"\"Regex pattern to match and parse", "int. Other data structures (dict, list, etc) must be serialized.", "value is None: # pragma: no cover return value for", "key is not None and value is not None: try:", "except RuntimeError as e: self.log.error(e) return None @staticmethod def _decode_binary(data):", "set(variables): # recursion over set to handle duplicates # pull", "# TODO: need to verify if core still sends improper", "if variable_type == 'BinaryArray': value = json.loads(value, object_pairs_hook=OrderedDict) values =", "de-serialized value from the key/value store. \"\"\" try: return json.loads(value,", "e: self.log.error(e) return None @staticmethod def _decode_binary(data): \"\"\"Return decoded bytes", "bytes): # v = v.encode('utf-8') v = base64.b64encode(v).decode('utf-8') value_encoded.append(v) value", "None. Would like to be able to say if value", "retrieved from DB \"\"\" # TODO: need to verify if", "provided data has proper structure for TC Entity Array.\"\"\" for", "= json.dumps(v) # for KeyValueArray with nested dict/list type replace", "not None: value = self.tcex.key_value_store.read(self._context, key.strip()) else: self.log.warning('The key field", "playbook variable.\"\"\" variable_pattern = r'#([A-Za-z]+)' # match literal (#App,#Trigger) at", "if core still sends improper JSON for KeyValueArrays if data", "True if provided data has proper structure for Key Value", "just the string. value = re.sub(variable, v, value) return value", "variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern +=", "Iterable class PlaybooksBase: \"\"\"TcEx Playbook Module Base Class Args: tcex", "provided for TcEntityArray.') # self.log.trace(f'pb create - context: {self._context}, key:", "provided to Playbook Class. **Example Variable Format**:: ['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\"", "def _is_tc_entity(data): \"\"\"Return True if provided data has proper structure", "({e})') elif variable_type == 'StringArray': if embedded: value = self._read_embedded(value)", "bool before int as python says a bool is an", "name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array) variable_pattern", "except RuntimeError as e: self.log.error(e) return None if value is", "json.dumps(v) # for KeyValueArray with nested dict/list type replace the", "has proper structure for TC Entity.\"\"\" if data is None:", "[] for v in value: if v is not None", "int to str value_coerced = [] for v in self._load_value(value):", "+= r':([\\d]+)' # app id (:7979) variable_pattern += r':([A-Za-z0-9_\\.\\-\\[\\]]+)' #", "if value is None: return value if variable_type == 'Binary':", "return value @property def _variable_pattern(self): \"\"\"Regex pattern to match and", "if isinstance(v, (dict, list)): v = json.dumps(v) # for KeyValueArray", "context (str): The Redis context (hash). output_variables (list): The requested", "data is None: return False return all(x in data for", "library import base64 import json import re from collections import", "{key}, value: {value}') return value def _read_embedded(self, value): \"\"\"Read method", "require a kv-specific # version of this method that gets", "retrieved from DB. If there are no keys/variables the raw", "value in Redis if applicable.\"\"\" if key is None: #", "variable_type in ['TCEntityArray', 'TCEnhancedEntity', 'TCEnhancedEntityArray']: value = self._load_value(value) # self.log.trace(f'pb", "\"two\", \"three\"] Examples 1: Input: \"This input has a embedded", "variable_type == 'TCEntity': value = self._load_value(value) return value def _read_array(self,", "coerce bool before int as python says a bool is", "data provided for Binary.') # if not isinstance(v, bytes): #", "validate=True): \"\"\"Create the value in Redis if applicable.\"\"\" if key", "unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if embedded: value", "False return all(x in data for x in ['id', 'value',", "= parsed_variable.get('name') variable_type = parsed_variable.get('type') # store the variables in", "pragma: no cover # for data written an upstream java", "['#App:1234:status!String', '#App:1234:status_code!String'] \"\"\" self._output_variables_by_name = {} self._output_variables_by_type = {} for", "variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace the correct", "Value Array.\"\"\" for d in data: if not self._is_key_value(d): return", "store. \"\"\" try: return json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e:", "is the wild-wild west, don't validate it if variable_type !=", "self._output_variables_by_type[f'{variable_name}-{variable_type}'] = {'variable': ov} def _read(self, key, embedded=True, b64decode=True, decode=False):", "the output variables provided to Playbook Class. **Example Variable Format**::", "data = self.tcex.key_value_store.create(self._context, key.strip(), value) except RuntimeError as e: self.log.error(e)", "if not isinstance(v, bytes): # v = v.encode('utf-8') v =", "method of CRUD operation for raw data. ..important:: Raw data", "'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self): \"\"\"Return list", "= json.loads(value, object_pairs_hook=OrderedDict) except ValueError as e: # pragma: no", "value (str): The value to parsed and updated from the", "The de-serialized value from the key/value store. \"\"\" try: return", "loaded JSON value or raise an error. Args: value (str):", "== 'TCEntity': value = self._load_value(value) return value def _read_array(self, key,", "# pragma: no cover # for data written an upstream", "This method will automatically covert variables embedded in a string", "key.strip(), value) except RuntimeError as e: self.log.error(e) return None @staticmethod", "= self._read_embedded(value) # convert int to str value_coerced = []", "value ({value}) to a string (\"{str(value).lower()}\").') value = str(value).lower() #", "Args: value (str): The data from key/value store. Raises: RuntimeError:", "raise RuntimeError('Invalid data provided for String.') elif variable_type == 'TCEntity':", "# match literal (#App,#Trigger) at beginning of String variable_pattern +=", "error. Args: value (str): The data from key/value store. Raises:", "as python says a bool is an int if isinstance(value,", "\"\"\"Wrap keyvalue embedded variable in double quotes. Args: data (str):", "read from the DB. Returns: (str): Results retrieved from DB.", "r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching", "typesd.\"\"\" return self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue", "the case where a variable # is embedded multiple times", "The data to write to the DB. Returns: (str): Result", "if variable_type == 'Binary': # if not isinstance(value, bytes): #", "a kv-specific # version of this method that gets the", "can have embedded variables. * Only String and KeyValueArray variables", "variable in double quotes. Args: data (str): The data with", "an iterable) if variable_type == 'BinaryArray': value_encoded = [] for", "self._variable_single_types + self._variable_array_types def _wrap_embedded_keyvalue(self, data): \"\"\"Wrap keyvalue embedded variable", "or int. Other data structures (dict, list, etc) must be", "and not isinstance(v, (type(None), str)): raise RuntimeError('Invalid data provided for", "r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom variable_pattern += r'[A-Za-z0-9_-]+))' #", "(array) variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array) variable_pattern +=", "that gets the entire list/dict instead of just the string.", "(\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse, var).group(0) # reformat to replace", "def parse_variable(self, variable): # pragma: no cover \"\"\"Set placeholder for", "when data can't be loaded as JSON data. Returns: any:", "# version of this method that gets the entire list/dict", "bool): # coerce bool to str type self.log.warning(f'Coercing bool value", "= values elif variable_type == 'KeyValueArray': # embedded variable can", "variable) self._variable_parse = re.compile(self._variable_pattern) # match embedded variables without quotes", "if validate and not self._is_key_value_array(value): raise RuntimeError('Invalid data provided for", "'BinaryArray': value_encoded = [] for v in value: if v", "to the DB. value (bytes|int|string): The data to write to", "TC Entity Array.\"\"\" for d in data: if not self._is_tc_entity(d):", "r':([A-Za-z0-9_\\.\\-\\[\\]]+)' # variable name (:variable_name) variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable", "dict) or not self._is_tc_entity(value)): raise RuntimeError('Invalid data provided for TcEntity.')", "parse the variable to get individual parts parsed_variable = self.parse_variable(ov)", "== 'Binary': value = self._load_value(value) if b64decode: value = base64.b64decode(value)", "JSON load data \"{value}\" ({e}).') def _parse_output_variables(self): \"\"\"Parse the output", "a embedded #App:7979:variable_name!String\" }, { \"key\": \"string array\", \"value\": #App:7979:variable_name!StringArray", "= data.decode('latin-1') return data @staticmethod def _is_key_value(data): \"\"\"Return True if", "UnicodeDecodeError: # pragma: no cover # for data written an", "operation for raw data. ..important:: Bytes input will be returned", "provided for TcEntity.') # self.log.trace(f'pb create - context: {self._context}, key:", "Entity.\"\"\" if data is None: return False return all(x in", "handling data written by java apps.\"\"\" try: data = data.decode('utf-8')", "# coerce bool to str type self.log.warning(f'Coercing bool value ({value})", "in kv/kvarrays that # are None. Would like to be", "= re.compile(fr'^{self._variable_pattern}$') # capture variable parts (exactly a variable) self._variable_parse", "the loaded JSON value or raise an error. Args: value", "#App:7979:variable_name!StringArray: [\"one\", \"two\", \"three\"] Examples 1: Input: \"This input has", "Redis context (hash). output_variables (list): The requested output variables. \"\"\"", "duplicates # pull (#App:1441:embedded_string!String) from (\": #App:1441:embedded_string!String) variable_string = re.search(self._variable_parse,", "False return True @staticmethod def _is_tc_entity(data): \"\"\"Return True if provided", "is no way to determine data from redis originated as", "+= r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)'", "value = self._read_embedded(value) try: value = json.loads(value, object_pairs_hook=OrderedDict) except ValueError", "provided for KeyValueArray.') elif variable_type == 'StringArray': value_coerced = []", "type (array) variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type variable_pattern +=", "the Class properties.\"\"\" self.tcex = tcex self._context = context self._output_variables", "None and value is not None: try: data = self.tcex.key_value_store.create(self._context,", "input will be returned a as string as there is", "int)): self.log.warning(f'Coercing float/int value ({value}) to a string (\"{str(value)}\").') value", "\"three\"] Examples 1: Input: \"This input has a embedded #App:7979:variable_name!String\"", "can be unquoted, which breaks JSON. value = self._wrap_embedded_keyvalue(value) if", "be serialized. Args: key (str): The variable to write to", "\"\"\" data = None if key is not None and", "Returns: any: The de-serialized value from the key/value store. \"\"\"", "# capture variable parts (exactly a variable) self._variable_parse = re.compile(self._variable_pattern)", "None: self.log.warning('The key or value field is None.') return None", "a string (\"{str(value).lower()}\").') value = str(value).lower() # coerce int to", "self.log.error(e) return None def _create_array(self, key, value, validate=True): \"\"\"Create the", "Raise error when data can't be loaded as JSON data.", "only, handling the case where a variable # is embedded", "a as string as there is no way to determine", "[ 'Binary', 'KeyValue', 'String', 'TCEntity', 'TCEnhancedEntity', ] @property def _variable_types(self):" ]
[ "and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from", "None, \"The vocabulary file that the BERT model was trained", "2.0 (the \"License\"); # you may not use this file", "When false, uses TF32 on A100 and FP32 on V100", "master_process = True training_hooks = [] global_batch_size = FLAGS.train_batch_size *", "be printed. \" \"A number of warnings are expected for", "Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\",", "accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return {", "FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90", "\"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained BERT model).\")", "* FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for", "than this will be truncated, and sequences shorter \" \"than", "predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() #", "tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes", "FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities)", "data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file,", "csv import os import modeling import optimization import tokenization import", "np import tf_metrics flags = tf.flags FLAGS = flags.FLAGS ##", "\"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\",", "num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time =", "probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL:", "with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(),", "FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples =", "for uncased \" \"models and False for cased models.\") flags.DEFINE_integer(", "FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank()", "must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings:", "= processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True", "tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits,", "tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='')", "type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint", "num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count", "tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90 * 1000)", "global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped)", "use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training,", "mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids,", "= start_index + num_examples_per_rank + 1 else: start_index = hvd.rank()", "We do # not use Dataset.from_generator() because that uses tf.py_func", "disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions", "JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu", "axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels *", "tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions,", "often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many", "num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec(", "pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits):", "tf.int64, but the TPU only supports tf.int32. # So cast", "uses TF32 on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\",", "= tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec", "steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number", "Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The", "input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask')", "%s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples =", "optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn", "Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64),", "dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd", "*****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"", "License for the specific language governing permissions and # limitations", "flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should contain the", "task on the entire # segment. # # If you", "init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op =", "hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if", "%0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total", "with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for", "reserved. # Copyright 2018 The Google AI Language Team Authors.", "size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable", "num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def", "tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length)", "return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else:", "= tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\",", "utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import * import", "the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")", "key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples", "Confidence Level 100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency", "import optimization import tokenization import tensorflow as tf import horovod.tensorflow", "ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\")", "num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import", "output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"*****", "num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time =", "is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed", "FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0) hvd_rank =", "= tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'],", "} else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss)", "is not None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat()", "int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps *", "else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if", "file corresponding to the pre-trained BERT model. \" \"This specifies", "dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return", "eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences =", "hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index],", "(ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) =", "1 else: start_index = hvd.rank() * num_examples_per_rank + remainder end_index", "print('Total node count before and after TF-TRT conversion:', num_nodes, '->',", "label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op", "pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, }", "d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d", "* FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0", "%d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\")", "in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences =", "time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import", "num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(),", "tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels", "\"Whether to lower case the input text. Should be True", "shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True", "for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0,", "label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples", "the pre-trained BERT model. \" \"This specifies the model architecture.\")", "FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode ==", "used by the Colab and # people who depend on", "predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\")", "key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s =", "## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes", "of `do_train`, `do_eval` or `do_predict' must be True.\") bert_config =", "name = %s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph", "is not used by this file but is still used", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100 *", "elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec", "to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If", "= [] all_segment_ids = [] all_label_ids = [] for feature", "tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() =", "%d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn =", "True, \"Whether to lower case the input text. Should be", "eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to call mixed", "# This is for demo purposes and does NOT scale", "optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type)", "= \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\",", "%0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second)", "[LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed =", "d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d", "init_string = \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\"", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for", "FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert()", "def input_fn(): \"\"\"The actual input function.\"\"\" # For training, we", "from __future__ import print_function import collections import csv import os", "def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if", "Team Authors. # # Licensed under the Apache License, Version", "ValueError(\"Task not found: %s\" % (task_name)) processor = processors[task_name]() label_list", "to in writing, software # distributed under the License is", "start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank", "data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s", "flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to", "\" \"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128,", "be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask = []", "## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir.", "Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])},", "on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT", "\", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name,", "or agreed to in writing, software # distributed under the", "doing a simple classification task on the entire # segment.", "str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed =", "to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example", "as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32,", "enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod", "tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape,", "Inference Time = %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count", "utils.create_glue_data import * import numpy as np import tf_metrics flags", "and sequences shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\",", "ops. When false, uses TF32 on A100 and FP32 on", "hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode,", "output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable(", "features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"]", "loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model(", "tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps =", "loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss =", "tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn # This function", "bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot", "compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu runs\")", "None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train:", "processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file,", "Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\",", "of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file", "if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration", "writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process:", "if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d", "FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN,", "compliance with the License. # You may obtain a copy", "__future__ import division from __future__ import print_function import collections import", "BERT model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None,", "0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences *", "scale to large data sets. We do # not use", "time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps *", "else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features(", "config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir", "/ global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index", "as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn,", "predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN,", "FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least one of", "tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn", "raise ValueError( \"At least one of `do_train`, `do_eval` or `do_predict'", "num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)", "dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids,", "# For eval, we want no shuffling and parallel reading", "init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for", "not use this file except in compliance with the License.", "flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient update\" \"Global", "task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate", "\"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size", "one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs,", "tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd", "get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth =", "you may not use this file except in compliance with", "\"If true, all of the warnings related to data processing", "flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform linear learning", "written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger", "batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time()", "bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars =", "[] all_segment_ids = [] all_label_ids = [] for feature in", "= get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities)", "for i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder", "# So cast all int64 to int32. for name in", "model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The", "os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running", "hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort()", "****\") for var in tvars: init_string = \"\" if var.name", "tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)}", "= tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids,", "flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total", "%s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if", "trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits,", "False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks", "one of `do_train`, `do_eval` or `do_predict' must be True.\") bert_config", "global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for Sentences", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "\"Whether to enable AMP ops. When false, uses TF32 on", "eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5,", "0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) *", "= file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not", "which is # not TPU compatible. The right way to", "(or other data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\",", "for n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\",", "transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1,", "inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch", "many steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1,", "False, \"Whether to run the model in inference mode on", "optimization import tokenization import tensorflow as tf import horovod.tensorflow as", "tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\",", "all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\"", "found: %s\" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels()", "8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial", "FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\")", "loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def", "\" \"Sequences longer than this will be truncated, and sequences", "and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least", "import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class", "to lower case the input text. Should be True for", "to perform linear learning rate warmup for. \" \"E.g., 0.1", "= FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto()", "num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25))", "this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")", "name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training,", "tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95 * 1000)", "tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec =", "tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences = %d\",", "predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in", "[] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config", "tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences =", "who depend on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder,", "(sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) =", "d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder))", "num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "# Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list)", "in list(example.keys()): t = example[name] if t.dtype == tf.int64: t", "lot of parallel reading and shuffling. # For eval, we", "tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op =", "governing permissions and # limitations under the License. \"\"\"BERT finetuning", "0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if", "False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op)", "loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops =", "0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod:", "hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0))", "perform linear learning rate warmup for. \" \"E.g., 0.1 =", "= file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)]", "The Google AI Language Team Authors. # # Licensed under", "output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\",", "rewrite if fp16 to enable graph rewrite if FLAGS.amp: loss_scaler", "tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities']", "tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks =", "= %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size", "\"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type", "d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def", "train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need", "passed to Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids", "segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) =", "Time W/O Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead,", "'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape,", "/ train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99 *", "graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter", "\"\"\"The actual input function.\"\"\" # For training, we want a", "name = %s, shape = %s\" % (name, features[name].shape)) input_ids", "use sequence length %d because the BERT model \" \"was", "the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task", "output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn #", "TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32),", "name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1)", "rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0),", "output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training:", "tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from", "0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg =", "tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))", "= tf.to_int32(t) example[name] = t return example def input_fn(): \"\"\"The", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return", "None or hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars,", "= tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits =", "token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are doing", "FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences", "= tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90 *", "evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an", "to data processing will be printed. \" \"A number of", "tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op =", "output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op()", "0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size()", "+ FP) * (TP + FN) * (TN + FP)", "<< 20) - 1000, precision_mode = \"FP16\" if FLAGS.amp else", "labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\"", "= file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)]", "label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,", "tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer,", "FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index", "checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from estimator\")", "\"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\"", "import absolute_import from __future__ import division from __future__ import print_function", "mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to", "def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn`", "= max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95", "for var in tvars: init_string = \"\" if var.name in", "processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks", "_decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config,", "all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features)", "file except in compliance with the License. # You may", "axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids,", "= %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__", "if hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d", "initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if", "= hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1:", "d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None:", "} tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in", "\"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples,", "= time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps", "time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers", "hvd=None if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn,", "tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\",", "= %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms)", "= tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant(", "ValueError( \"At least one of `do_train`, `do_eval` or `do_predict' must", "verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\") flags.mark_flag_as_required(\"bert_config_file\")", "% (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids", "FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod", "# Copyright 2018 The Google AI Language Team Authors. #", "max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 =", "writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks,", "predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1])", "after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1", "eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks)", "example def input_fn(): \"\"\"The actual input function.\"\"\" # For training,", "= tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids", "steps before gradient update\" \"Global batch size = num_accumulation_steps *", "tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT)", "\"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether", "= %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped)", "because that uses tf.py_func which is # not TPU compatible.", "* FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for", "= hvd.rank() * num_examples_per_rank + remainder end_index = start_index +", "\"Cannot use sequence length %d because the BERT model \"", "None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process:", "but is still used by the Colab and # people", "= np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list)", "Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\")", "KIND, either express or implied. # See the License for", "\"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train", "hvd is not None: d = d.shard(hvd.size(), hvd.rank()) d =", "-tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return", "* FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod:", "return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training,", "converter.convert() print('Total node count before and after TF-TRT conversion:', num_nodes,", "+ FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op,", "ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\")", "features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if", "training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\",", "input_fn(): \"\"\"The actual input function.\"\"\" # For training, we want", "predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\")", "tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map)", "= %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level", "'->', len(frozen_graph.node)) print('TRT node count:', len([1 for n in frozen_graph.node", "= (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph", "input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features) # This", "predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8))", "MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions)", "(the \"License\"); # you may not use this file except", "SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates", "and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum", "in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as", "input data dir. Should contain the .tsv files (or other", "num_examples = len(features) # This is for demo purposes and", "on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length", "FN) / ((TP + FP) * (TP + FN) *", "nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\" if", "W/O Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count", "setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors =", "= len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames =", "this file but is still used by the Colab and", "save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None,", "output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits,", "\"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from __future__ import", "- 1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4,", "for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn():", "tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key:", "Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence", "\"Number of accumulation steps before gradient update\" \"Global batch size", "# # Unless required by applicable law or agreed to", "{ \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, }", "if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise", "TPU compatible. The right way to load data is with", "numpy as np import tf_metrics flags = tf.flags FLAGS =", "epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to", "eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\",", "1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True,", "flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT model was", "warmup for. \" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\",", "config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\")", "we want no shuffling and parallel reading doesn't matter. d", "model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings,", "initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\"", "closure to be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask", "tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size =", "files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config", "initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable", "\"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size()", "hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply(", "(TP + FN) * (TN + FP) * (TN +", "contain the .tsv files (or other data files) \" \"for", "\"The maximum total input sequence length after WordPiece tokenization. \"", "node count:', len([1 for n in frozen_graph.node if str(n.op) ==", "%s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes", "flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool(", "implied. # See the License for the specific language governing", "all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples =", "record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def", "== tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd,", "size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder(", "d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d =", "= %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder", "(hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank())", "sequence length %d because the BERT model \" \"was only", "(num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1 else: start_index", "features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode", "%d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size()", "= %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size)", "time_list.sort() # Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead =", "tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if", "FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\":", "dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key]))", "ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference", ": adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually", "\"\"\"The actual input function.\"\"\" num_examples = len(features) # This is", "for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability)", "name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\" example =", "max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time", "do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size = FLAGS.train_batch_size", "# tf.Example only supports tf.int64, but the TPU only supports", "training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config", "\"The config json file corresponding to the pre-trained BERT model.", "converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000,", "start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint,", "99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if", "train_examples = None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size,", "Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright", "dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits)", "else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for", "%d because the BERT model \" \"was only trained up", "# In the demo, we are doing a simple classification", "train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size *", "tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\":", "= d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags()", "= %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\"", "= features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training =", "model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank])", "estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in", "eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead", "= os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval", "sequences shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False,", "def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init()", "all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input function.\"\"\" num_examples", "train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT model", "mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def", "be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise", "\" \"A number of warnings are expected for a normal", "__future__ import print_function import collections import csv import os import", "Unless required by applicable law or agreed to in writing,", "* import numpy as np import tf_metrics flags = tf.flags", "None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate,", "batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate", "feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The", "shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training:", "label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec", "Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all", "Variables ****\") for var in tvars: init_string = \"\" if", "{ \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy", "Confidence Level 50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency", "num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator", "the specific language governing permissions and # limitations under the", "input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids", "tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids,", "segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {}", "= len(features) # This is for demo purposes and does", "are expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size,", "= d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn", "(int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 =", "use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value", "log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in", "predictions=probabilities) return output_spec return model_fn # This function is not", "return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions", "= processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)", "tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average", "train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() -", "do # not use Dataset.from_generator() because that uses tf.py_func which", "// hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank() <", "master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list,", "= features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids =", "(TN + FP) * (TN + FN)) ** 0.5 MCC_op", "large data sets. We do # not use Dataset.from_generator() because", "%0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) =", "Overhead = %0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count -", "and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples,", "BERT model \" \"was only trained up to sequence length", "tvars: init_string = \"\" if var.name in initialized_variable_names: init_string =", "tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64),", "batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for", "throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list)", "Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size,", "eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time()", "= %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file =", "precision_mode = \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000", "all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32),", "data sets. We do # not use Dataset.from_generator() because that", "tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape,", "hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size,", "in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences =", "= None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank,", "`input_fn` closure to be passed to Estimator.\"\"\" all_input_ids = []", "= FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() ==", "of the warnings related to data processing will be printed.", "= tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss,", "to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform", "from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity", "files (or other data files) \" \"for the task.\") flags.DEFINE_string(", "= %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision =", "= %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples", "train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second =", "= (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50", "modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\")", "var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op", "tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels,", "None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process", "and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss,", "= utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor,", "raise ValueError(\"Task not found: %s\" % (task_name)) processor = processors[task_name]()", "tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need", "shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if", "- training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead =", "training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\",", "None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key", "TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to perform.\")", "This is for demo purposes and does NOT scale to", "* (TN + FP) * (TN + FN)) ** 0.5", "Level 90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) *", "segment. # # If you want to use the token-level", "0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) *", "hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process", "input text. Should be True for uncased \" \"models and", "i in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder =", "estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list,", "cast all int64 to int32. for name in list(example.keys()): t", "run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether", "'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def", "for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training", "Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line", "Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size", "\"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run", "init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss',", "run the model in inference mode on the test set.\")", "'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask,", "= flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input", "= training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 /", "if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())]", "\"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1", "often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often", "absolute_import from __future__ import division from __future__ import print_function import", "= tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: #", "tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\",", "= tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\":", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99", "tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids =", "not None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d", "= %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples =", "model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else", "= %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder", "probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels,", "from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in", "Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time", "BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output", "to Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids =", "the .tsv files (or other data files) \" \"for the", "def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn`", "the demo, we are doing a simple classification task on", "Colab and # people who depend on it. def input_fn_builder(features,", "eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\"", "You may obtain a copy of the License at #", "in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time", "\"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\"", "model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from", "all int64 to int32. for name in list(example.keys()): t =", "FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir,", "= %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference", "== tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode,", "FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples", "%s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key,", "% hvd.size() if hvd.rank() < remainder: start_index = hvd.rank() *", "%0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics", "f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions)", "hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process =", "tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features", "> bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d because", "len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank()", "num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps =", "graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec =", "tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size =", "is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples,", "\"\"\"Decodes a record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record,", "if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor,", "eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size", "predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"*****", "tf.int64: t = tf.to_int32(t) example[name] = t return example def", "FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder(", "precision graph rewrite if fp16 to enable graph rewrite if", "tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()):", "= time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as", "not FLAGS.do_predict: raise ValueError( \"At least one of `do_train`, `do_eval`", "90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks =", "in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps", "(name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids =", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT)", "var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name =", "\"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\")", "[os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i", "\"do_predict\", False, \"Whether to run the model in inference mode", "tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var", "if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences", "True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError(", "FN) * (TN + FP) * (TN + FN)) **", "= {} if init_checkpoint and (hvd is None or hvd.rank()", "the warnings related to data processing will be printed. \"", "train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for", "***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape", "= None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if", "= processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs)", "\"Whether to run the model in inference mode on the", "= tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer())", "tokenization. \" \"Sequences longer than this will be truncated, and", "tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames,", "= max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second", "/ predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences", "return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\")", "% (key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir)", "output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL:", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training", "the entire # segment. # # If you want to", "tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is not", "License. # You may obtain a copy of the License", "Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size)", "# Need to call mixed precision graph rewrite if fp16", "Confidence Level 99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency", "probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0',", "use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are doing a", "= True training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps", "dir. Should contain the .tsv files (or other data files)", "= tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC,", "\"Total number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1,", "if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph =", "entire # segment. # # If you want to use", "assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in", "%d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True,", "(init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences", "bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn`", "num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size()", "= tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op", "`do_eval` or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if", "tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size =", "tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50 * 1000)", "loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return", "tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps", "+ FN) * (TN + FP) * (TN + FN))", "0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg =", "and not FLAGS.do_predict: raise ValueError( \"At least one of `do_train`,", "master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}:", "permissions and # limitations under the License. \"\"\"BERT finetuning runner.\"\"\"", "predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids,", "'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode", "(c) 2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018", "the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The", "d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)", "FP) * (TN + FN)) ** 0.5 MCC_op = tf.group(FN_op,", "utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\":", "= %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision =", "1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95 *", "seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time", "in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string = \",", "if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps,", "create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars", "Confidence Level 90 (ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency", "model checkpoints will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\",", "segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids')", "as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()):", "from __future__ import division from __future__ import print_function import collections", "the input text. Should be True for uncased \" \"models", "* (TN + FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op,", "Removing outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) *", "= %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps) train_input_fn", "(num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if", "input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names =", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "= %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\")", "rights reserved. # Copyright 2018 The Google AI Language Team", "tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def", "the BERT model \" \"was only trained up to sequence", "In the demo, we are doing a simple classification task", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "related to data processing will be printed. \" \"A number", "flags.DEFINE_string( \"output_dir\", None, \"The output directory where the model checkpoints", "= { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length],", "probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto()", "eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks =", "modeling import optimization import tokenization import tensorflow as tf import", "on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run", "BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the", "required by applicable law or agreed to in writing, software", "shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids,", "run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps", "text. Should be True for uncased \" \"models and False", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss", "= \", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name", "# I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits =", "for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size)", "to enable AMP ops. When false, uses TF32 on A100", "init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps,", "tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() =", "all_segment_ids = [] all_label_ids = [] for feature in features:", "after WordPiece tokenization. \" \"Sequences longer than this will be", "= max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 /", "FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string", "agreed to in writing, software # distributed under the License", "Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)", "%d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch", "use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names =", "or hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)", "distributed under the License is distributed on an \"AS IS\"", "the model checkpoints will be written.\") ## Other parameters flags.DEFINE_string(", "name_to_features) # tf.Example only supports tf.int64, but the TPU only", "train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with", "tf import horovod.tensorflow as hvd import time from utils.utils import", "a simple classification task on the entire # segment. #", "tf_metrics flags = tf.flags FLAGS = flags.FLAGS ## Required parameters", "size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for", "= tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() #", "input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else", "else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape", "dtype=tf.int32), }) if is_training: if hvd is not None: d", "example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64,", "* 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000)", "# limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__", "dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = { \"cola\":", "remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index +", "flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\")", "expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length,", "%0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) =", "8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch", "len(frozen_graph.node)) print('TRT node count:', len([1 for n in frozen_graph.node if", "key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps =", "or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a", "task_name not in processors: raise ValueError(\"Task not found: %s\" %", "\"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\",", "input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time =", "+ remainder end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder(", "example[name] = t return example def input_fn(): \"\"\"The actual input", "= num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP", "ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not", "{\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode ==", "if not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps,", "print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to", "input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\"", "ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\")", "parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string(", "on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length", "Level 50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f", "= tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits,", "ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file", "matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is not", "in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s,", "batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for", "'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32,", "want a lot of parallel reading and shuffling. # For", "tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities)", "people who depend on it. def input_fn_builder(features, batch_size, seq_length, is_training,", "TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for", "accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 =", "OR CONDITIONS OF ANY KIND, either express or implied. #", "= [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples)", "reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd", "= tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs", "to be passed to Estimator.\"\"\" all_input_ids = [] all_input_mask =", "FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train:", "the License is distributed on an \"AS IS\" BASIS, #", "log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss", "training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training", "an `input_fn` closure to be passed to Estimator.\"\"\" name_to_features =", "def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates", "} def _decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow", "model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else", "(sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples", "%d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size,", "eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to", "(hvd is None or hvd.rank() == 0): (assignment_map, initialized_variable_names )", "TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length =", "Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\")", "tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer,", "task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the", "= tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\",", "of warnings are expected for a normal SQuAD evaluation.\") def", "input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we", "= %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\",", "%d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\",", "is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result =", "1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time =", "law or agreed to in writing, software # distributed under", "flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string(", "time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput", "import tokenization import tensorflow as tf import horovod.tensorflow as hvd", "set_affinity import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import", "parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should contain", "processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process", "= time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time", "flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False,", "flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When false, uses", "to enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op", "tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss')", "use the token-level output, use model.get_sequence_output() # instead. output_layer =", "sequence length after WordPiece tokenization. \" \"Sequences longer than this", "of accumulation steps before gradient update\" \"Global batch size =", "name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels,", "still used by the Colab and # people who depend", "tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars:", "Verbosity from utils.create_glue_data import * import numpy as np import", "input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if", "may obtain a copy of the License at # #", "FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank", "MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\":", "1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables()", "collections import csv import os import modeling import optimization import", "return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels,", "os import modeling import optimization import tokenization import tensorflow as", "loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, }", "flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total", "in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\" %", "hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd)", "Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn =", "= model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod", "model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size],", "classification task on the entire # segment. # # If", "# not TPU compatible. The right way to load data", "== tf.int64: t = tf.to_int32(t) example[name] = t return example", "initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape", "flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to perform.\") flags.DEFINE_float(", "\"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial", "may not use this file except in compliance with the", "return output_spec return model_fn # This function is not used", "is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count before", "tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False,", "tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None,", "\"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph", "* 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list)", "if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else", "examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)", "len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False", "learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\"", "(training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead", "this file except in compliance with the License. # You", "compatible. The right way to load data is with TFRecordReader.", "= d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return", "tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn", "size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision", "== 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if", "save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print", "[num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout", "FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions)", "Training Time = %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps", "use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs to", "init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape =", "purposes and does NOT scale to large data sets. We", "start_index = hvd.rank() * num_examples_per_rank + remainder end_index = start_index", "f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy,", "tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record to a", "num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features,", "# # Licensed under the Apache License, Version 2.0 (the", "to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size", "dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\")", "if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name", "learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\")", "this will be truncated, and sequences shorter \" \"than this", "utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import Verbosity from", "number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion", "number of warnings are expected for a normal SQuAD evaluation.\")", "= features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN)", "FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f for Sentences", "tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names,", "flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding to the", "TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC", "right way to load data is with TFRecordReader. d =", "sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key,", "= tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids,", "hvd=None): \"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\"", "%s%s\", var.name, var.shape, init_string) output_spec = None if mode ==", "global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index =", "import print_function import collections import csv import os import modeling", "avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(),", "= modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) #", "tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and", "num_examples_per_rank + 1 else: start_index = hvd.rank() * num_examples_per_rank +", "= estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list =", "\"data_dir\", None, \"The input data dir. Should contain the .tsv", "Need to call mixed precision graph rewrite if fp16 to", "labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\":", "to call mixed precision graph rewrite if fp16 to enable", "2018 The Google AI Language Team Authors. # # Licensed", "the token-level output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output()", "of parallel reading and shuffling. # For eval, we want", "%0.2f for Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total", "* 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list)", "in processors: raise ValueError(\"Task not found: %s\" % (task_name)) processor", "= %s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph =", "Inference Time W/O Overhead = %0.2f for Sentences = %d\",", "* train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When", "labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel(", "or implied. # See the License for the specific language", "that the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\", None,", "master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\")", "tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction", "Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp", "range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples) %", "if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t", "all_input_mask = [] all_segment_ids = [] all_label_ids = [] for", "flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence length after", "passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\":", "logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss,", "input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph,", "shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32,", "not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At least one", "tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string =", "import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data import *", "Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\",", "\"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),", "= %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True,", "main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors", "name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary", "for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1,", "all_input_ids = [] all_input_mask = [] all_segment_ids = [] all_label_ids", "classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids,", "num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops.", "output_type=tf.int32) if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions)", "\"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features", "input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time =", "task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss =", "label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids,", "not found: %s\" % (task_name)) processor = processors[task_name]() label_list =", "global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config =", "* (TP + FN) * (TN + FP) * (TN", "(None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings)", "is still used by the Colab and # people who", "we want a lot of parallel reading and shuffling. #", "not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks)", "NOT scale to large data sets. We do # not", "def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth", "input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\"", "0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) *", "hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in prediction)", "len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as", "XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use Horovod for", "= features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training", "\"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy =", "int64 to int32. for name in list(example.keys()): t = example[name]", "where the model checkpoints will be written.\") ## Other parameters", "and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:',", "None: d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d =", "== 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map)", "= tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op", "* 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences", "None, \"Initial checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool(", "shape = %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask", "evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch", "= str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla:", "d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record,", "* FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)])", "np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) *", "closure to be passed to Estimator.\"\"\" name_to_features = { \"input_ids\":", "if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running", "= optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps,", "cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\",", "if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir,", "per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0',", "prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list", "or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length", "language governing permissions and # limitations under the License. \"\"\"BERT", "for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape =", "name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities)", "init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for", "in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total", "mode=mode, predictions=probabilities) return output_spec return model_fn # This function is", "= modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables", "hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() >", "1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second},", "= %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms)", "\"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids,", "1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size", "\"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to", "to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether to use", "= [] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids)", "printed. \" \"A number of warnings are expected for a", "to use the token-level output, use model.get_sequence_output() # instead. output_layer", "* hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else", "[num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with", "\"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features):", "def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None):", "initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer", "(assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging:", "= tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if", "+ 1 else: start_index = hvd.rank() * num_examples_per_rank + remainder", "warnings are expected for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file,", "FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length,", "FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name ==", "# If you want to use the token-level output, use", "== tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec(", "update\" \"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True,", "demo purposes and does NOT scale to large data sets.", "= tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = []", "Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\"", "init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for", "= %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file,", "cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\",", "= tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss =", "= %s%s\", var.name, var.shape, init_string) output_spec = None if mode", "data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids,", "models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence length", "> 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp:", "%d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead", "(usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether", "tf.py_func which is # not TPU compatible. The right way", "function.\"\"\" # For training, we want a lot of parallel", "Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\"", "seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file", "simple classification task on the entire # segment. # #", "tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\",", "dummy_op = tf.no_op() # Need to call mixed precision graph", "# people who depend on it. def input_fn_builder(features, batch_size, seq_length,", "Time W/O Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead,", "d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch(", "checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True,", "- eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup)", "%d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size,", "tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record,", "Level 99 (ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "steps = %d\", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length,", "\" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json", "False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total", "tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1,", "dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True)", "output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias =", "num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list)", "\"How many steps to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\",", "import horovod.tensorflow as hvd import time from utils.utils import LogEvalRunHook,", "FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC,", "drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time = time.time()", "the model in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\",", "shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\":", "by the Colab and # people who depend on it.", "flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number", "\"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node", "import tensorflow as tf import horovod.tensorflow as hvd import time", "global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput", "examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)", "FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif", "# instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights =", "model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not", "hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps", "enable AMP ops. When false, uses TF32 on A100 and", "\"Initial checkpoint (usually from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\",", "in writing, software # distributed under the License is distributed", "cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\",", "\"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval", "with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask", "f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps,", "file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\")", "\"max_seq_length\", 128, \"The maximum total input sequence length after WordPiece", "5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether", "EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length =", "%0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) =", "hvd=None if not FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn,", "FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if", "task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op", "batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training, input_ids,", "if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length", "the dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the", "output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits", "perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of training to perform linear", "(ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90", "32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch", "None, \"The output directory where the model checkpoints will be", "as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint,", "TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name", "will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\",", "def input_fn(): \"\"\"The actual input function.\"\"\" num_examples = len(features) #", "length after WordPiece tokenization. \" \"Sequences longer than this will", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples))", "model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn` for", "if hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index", "(int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 =", "data dir. Should contain the .tsv files (or other data", "= os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"*****", "+ \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list =", "tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key,", "FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task not found:", "yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability in prediction) +", "input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names", "= tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op", "actual input function.\"\"\" num_examples = len(features) # This is for", "assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in", "1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total", "mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec =", "for key in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s", "%s, shape = %s%s\", var.name, var.shape, init_string) output_spec = None", "by this file but is still used by the Colab", "features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"]", "Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput", "\"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for", "seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids,", "tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\",", "if init_checkpoint and (hvd is None or hvd.rank() == 0):", "== \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss)", "predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\":", "the License for the specific language governing permissions and #", "examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)", "train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\"", "be True for uncased \" \"models and False for cased", "if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1", "= %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\")", "= %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O", "accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\")", "instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable(", "True, \"Whether to enable AMP ops. When false, uses TF32", "Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec)", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels,", "%s, shape = %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess,", "SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\",", "= tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits',", "of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model", "False, \"If true, all of the warnings related to data", "* 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f", "if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config)", "if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler)", "else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return", "will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename", "to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\":", "return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy =", "\"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch", "= tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config,", "processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\":", "\"A number of warnings are expected for a normal SQuAD", "init_string = \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape =", "finetuning runner.\"\"\" from __future__ import absolute_import from __future__ import division", "* (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1 else:", "\"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation", "= d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return", "output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"*****", "/ train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size *", "file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\")", "length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if", "json file corresponding to the pre-trained BERT model. \" \"This", "checkpoints will be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\",", "= %s, shape = %s\" % (name, features[name].shape)) input_ids =", "frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f:", "rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec(", "num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size =", "seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be", "print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars: init_string", "= [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for", "bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d because the", "time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead", "tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences = %d\", train_time_elapsed,", "License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from __future__", "save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"*****", "Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence", "if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False,", "# distributed under the License is distributed on an \"AS", "= tf.estimator.Estimator( model_fn=model_fn, config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length,", "\"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed", "# Unless required by applicable law or agreed to in", "\"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "TPU only supports tf.int32. # So cast all int64 to", "used by this file but is still used by the", "runner.\"\"\" from __future__ import absolute_import from __future__ import division from", "set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model in", "# Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list)", "false, uses TF32 on A100 and FP32 on V100 GPUS.\")", "tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(train_examples))", "all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if", "tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...')", "hvd.size() if hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1)", "{ \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),", "(ms) = %0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100", "the Apache License, Version 2.0 (the \"License\"); # you may", "start_index = 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")]", "If you want to use the token-level output, use model.get_sequence_output()", "on the entire # segment. # # If you want", "all of the warnings related to data processing will be", "training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\")", "segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training = (mode ==", "LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from", "True training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank", "'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode ==", "1000, \"How many steps to make in each estimator call.\")", "data processing will be printed. \" \"A number of warnings", "# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. #", "flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained BERT", "tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with", "train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp,", "* hvd.size() master_process = (hvd.rank() == 0) hvd_rank = hvd.rank()", "will be printed. \" \"A number of warnings are expected", "tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for Sentences =", "task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task", "MCC = (TP * TN - FP * FN) /", "config=run_config) if FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"*****", "\"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to", "on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where the model", "tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return { \"eval_accuracy\":", "max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 =", "loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "is_training: if hvd is not None: d = d.shard(hvd.size(), hvd.rank())", "pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case", "lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return input_fn", "predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead = %0.2f", "training, we want a lot of parallel reading and shuffling.", "end_index = start_index + num_examples_per_rank + 1 else: start_index =", "else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50", "%s, shape = %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"]", "for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\",", "and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features(", "function.\"\"\" num_examples = len(features) # This is for demo purposes", "config.gpu_options.visible_device_list = str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if", "= start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list),", "eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8))", "FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\",", "tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"): if is_training: # I.e.,", "False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of", "FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length,", "= tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF Horovod\") tf.compat.v1.logging.info(\"hvd.size()", "for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on", "== 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph", "as hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags", "cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input sequence", "outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)])", "flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\",", "= %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O", "FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\")", "remainder = len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index", "tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape,", "in range(hvd.size())] num_examples_per_rank = len(train_examples) // hvd.size() remainder = len(train_examples)", "train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size *", "= tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC =", "num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index =", "print_function import collections import csv import os import modeling import", "Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary", "eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in", "batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to", "be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False,", "want to use the token-level output, use model.get_sequence_output() # instead.", "= tf.no_op() # Need to call mixed precision graph rewrite", "not TPU compatible. The right way to load data is", "under the License is distributed on an \"AS IS\" BASIS,", "verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\"", "in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual", "Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\"", "is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file =", "str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict and", "tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var", "\"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The", "and shuffling. # For eval, we want no shuffling and", "file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod", "input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map,", "= eval_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation.", "sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size", "of training to perform linear learning rate warmup for. \"", "NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The Google", "= (TP * TN - FP * FN) / ((TP", "True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False, \"Whether", "Level 100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average", "the TPU only supports tf.int32. # So cast all int64", "modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In", "setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import", "***\") tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name", "float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s =", "hvd.rank() < remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index =", "config json file corresponding to the pre-trained BERT model. \"", "FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP,", "%0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir)", "tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder)) return d return", "file that the BERT model was trained on.\") flags.DEFINE_string( \"output_dir\",", "TF32 on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True,", "num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for n in", "var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string =", "from __future__ import absolute_import from __future__ import division from __future__", "example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] =", "length %d because the BERT model \" \"was only trained", "tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a", "%0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg", "with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length],", "= modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables", "training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model checkpoint.\")", "and (hvd is None or hvd.rank() == 0): (assignment_map, initialized_variable_names", "(MCC, MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids,", "num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=tmp_filenames, batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None", "= False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder)", "= {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode", "eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False,", "AI Language Team Authors. # # Licensed under the Apache", "hvd.rank() * num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank)", "tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\") flags.mark_flag_as_required(\"bert_config_file\") flags.mark_flag_as_required(\"output_dir\")", "coding=utf-8 # Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.", "run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the", "return example def input_fn(): \"\"\"The actual input function.\"\"\" # For", "None, \"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None,", "- FP * FN) / ((TP + FP) * (TP", "per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss,", "/ ((TP + FP) * (TP + FN) * (TN", "import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096", "for name in list(example.keys()): t = example[name] if t.dtype ==", "fp16 to enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1)", "tf.to_int32(t) example[name] = t return example def input_fn(): \"\"\"The actual", "TN - FP * FN) / ((TP + FP) *", "1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for", "** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\"))", "only supports tf.int32. # So cast all int64 to int32.", "= \"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\" writer.write(output_line)", "\" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name", "= max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99", "probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels", "os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results", "maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count before and", "end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames", "Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) *", "num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples)", "= converter.convert() print('Total node count before and after TF-TRT conversion:',", "Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST", "to the pre-trained BERT model. \" \"This specifies the model", "\"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else:", "tf.int32. # So cast all int64 to int32. for name", "ANY KIND, either express or implied. # See the License", "[] all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask)", "* global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f for", "= trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 90 (ms) = %0.2f\", cf_90", "= int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps", "FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90", "the License. # You may obtain a copy of the", "= processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length,", "output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt", "the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding", "t return example def input_fn(): \"\"\"The actual input function.\"\"\" #", "# See the License for the specific language governing permissions", "XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval and not", "Copyright 2018 The Google AI Language Team Authors. # #", "* 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f", "= { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor,", "tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities =", "Should contain the .tsv files (or other data files) \"", "Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process:", "to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to", "- training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if master_process:", "flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in each estimator", "num_classes=2, pos_indices=[1]) return { \"eval_accuracy\": accuracy, \"eval_f1\": f1, \"eval_loss\": loss,", "== tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config,", "tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd is None", "rate warmup for. \" \"E.g., 0.1 = 10% of training.\")", "flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The", "drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to be passed to", "%d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name", "TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN", "tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process", "directory where the model checkpoints will be written.\") ## Other", "name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec", "MnliProcessor, \"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and", "avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval", "no shuffling and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file)", "features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and", "from dllogger import Verbosity from utils.create_glue_data import * import numpy", "set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level =", "tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length)", "10, \"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000,", "output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size =", "= modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use", "* 1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\")", "output_spec return model_fn # This function is not used by", "# pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids,", "(total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids},", "flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\", False,", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "way to load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({", "demo, we are doing a simple classification task on the", "file but is still used by the Colab and #", "writing, software # distributed under the License is distributed on", "= tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None: d", "eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config,", "elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to", "V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\")", "128, \"The maximum total input sequence length after WordPiece tokenization.", "For training, we want a lot of parallel reading and", "tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod: hvd.init() processors = {", "truncated, and sequences shorter \" \"than this will be padded.\")", "%s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50", "initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"****", "mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size", "label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if", "output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits,", "is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables()", "tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape, init_string)", "as np import tf_metrics flags = tf.flags FLAGS = flags.FLAGS", "count:', len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp']))", "hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from", "\"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often", "all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32),", "* 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\":", "import time from utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity", "tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss',", "is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt:", "enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec", "= None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss,", "MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval", "num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples", "\"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\":", "FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss,", "Confidence Level 95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency", "input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names)", "%d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead", "+ (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate", "time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput", "FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples", "eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead =", "1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total", "= (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list = str(hvd.local_rank())", "= %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size)", "None, \"The input data dir. Should contain the .tsv files", "FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence length %d", "for class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time()", "= tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and (hvd is", "tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU", "f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate,", "tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process", "\"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning", "train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead =", "hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second", "= tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2, pos_indices=[1]) return {", "input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids')", "FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError( \"At", "conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node count:', len([1 for n", "batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure to", "FLAGS.horovod else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed", "to be passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length],", "depend on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None):", "= example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name]", "num_labels, use_one_hot_embeddings, init_checkpoint): tf_config = tf.compat.v1.ConfigProto() tf_config.gpu_options.allow_growth = True output_node_names", "1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput", "minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total node count", "Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.predict_batch_size)", "LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger", "corresponding to the pre-trained BERT model. \" \"This specifies the", "avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 =", "logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,", "label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num", "= sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) *", "return model_fn # This function is not used by this", "tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size =", "return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging =", "[os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank = len(train_examples) //", "\"warmup_proportion\", 0.1, \"Proportion of training to perform linear learning rate", "longer than this will be truncated, and sequences shorter \"", "output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops", "= ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids", "and does NOT scale to large data sets. We do", "tf.placeholder(tf.int32, shape, 'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids =", "with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\",", "= tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config,", "For eval, we want no shuffling and parallel reading doesn't", "Level 95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence", "TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter(", "tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask,", "metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name", "0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights,", "overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second)", "estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time() - train_start_time train_time_wo_overhead =", "task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file corresponding to", "0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) *", "closure for Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint:", "= %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key])))", "label_ids = features[\"label_ids\"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) if not", "= 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "= tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op", "if master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None,", "= [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with", "= %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference", "\"The output directory where the model checkpoints will be written.\")", "is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd) train_start_time =", "mixed precision graph rewrite if fp16 to enable graph rewrite", "Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS,", "else: start_index = hvd.rank() * num_examples_per_rank + remainder end_index =", "processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps", "for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of", "\"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config, num_labels,", "record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) #", "is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo,", "file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time", "= %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size)", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that", "under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import", "set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8,", "learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps,", "ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\":", "time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer:", "0.1, \"Proportion of training to perform linear learning rate warmup", "+ FP) * (TN + FN)) ** 0.5 MCC_op =", "= [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0", "FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to", ") frozen_graph = converter.convert() print('Total node count before and after", "d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)", "load data is with TFRecordReader. d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant(", "\"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples,", "if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\") flags.mark_flag_as_required(\"vocab_file\") flags.mark_flag_as_required(\"bert_config_file\") flags.mark_flag_as_required(\"output_dir\") tf.compat.v1.app.run()", "doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if hvd is", "get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) =", "# coding=utf-8 # Copyright (c) 2019 NVIDIA CORPORATION. All rights", "and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable", "Time = %0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count *", "\"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids,", "trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where the", "tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss,", "it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an", "if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) =", "file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num", "= tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN - FP", "{}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps =", "loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make", "= len(frozen_graph.node) print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert", "\"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" name_to_features", "False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run", "only supports tf.int64, but the TPU only supports tf.int32. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "\" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to", "time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers", "trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 <<", "False, \"Whether to run eval on the dev set.\") flags.DEFINE_bool(", "utils.utils import LogEvalRunHook, LogTrainRunHook, setup_xla_flags from utils.gpu_affinity import set_affinity import", "create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a", "specific language governing permissions and # limitations under the License.", "dev set.\") flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model", "Time = %0.2f for Sentences = %d\", train_time_elapsed, num_train_steps *", "tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy,", "predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits)", "'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None),", "graph rewrite if fp16 to enable graph rewrite if FLAGS.amp:", "maximum total input sequence length after WordPiece tokenization. \" \"Sequences", "output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss,", "tensorflow as tf import horovod.tensorflow as hvd import time from", "_decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\" example", "* global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second)", "{ \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"***", "if not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels,", "(training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead if", "call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient update\"", "tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num examples =", "in tvars: init_string = \"\" if var.name in initialized_variable_names: init_string", "0.5 MCC_op = tf.group(FN_op, TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return", "tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call mixed precision", "# you may not use this file except in compliance", "* global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total", "= num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second =", "50 (ms) = %0.2f\", cf_50 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s,", "a classification model.\"\"\" model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask,", "= %s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask =", "%d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch", "tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length],", "* 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list)", "shape = %s%s\", var.name, var.shape, init_string) output_spec = None if", "is for demo purposes and does NOT scale to large", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node)", "= metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops)", "\"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss", "10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the", "function is not used by this file but is still", "mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call", "'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids')", "= tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss, } tf.compat.v1.logging.info(\"***", "= %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps *", "d = d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100)", "hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps =", "return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,", "int32. for name in list(example.keys()): t = example[name] if t.dtype", "= [] all_input_mask = [] all_segment_ids = [] all_label_ids =", "prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size", "warnings related to data processing will be printed. \" \"A", "architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\")", "input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the demo, we are", "under the Apache License, Version 2.0 (the \"License\"); # you", "print('TRT node count:', len([1 for n in frozen_graph.node if str(n.op)", "(task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer(", "* FLAGS.predict_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list) * 0.50)])", "optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec(", "predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\") tf.compat.v1.logging.info(\"Batch size", "\"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1", "init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids,", "This function is not used by this file but is", "processors: raise ValueError(\"Task not found: %s\" % (task_name)) processor =", "predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead", "avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second", "if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) /", "token-level output, use model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size", "* FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames =", "tf.io.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): \"\"\"Decodes a record to", "= time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() -", "\"was only trained up to sequence length %d\" % (FLAGS.max_seq_length,", "os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running prediction*****\")", "trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode =", "Estimator.\"\"\" all_input_ids = [] all_input_mask = [] all_segment_ids = []", "global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank()", "estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list", "on it. def input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates", "\"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms)", "= tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return model_fn # This", "import * import numpy as np import tf_metrics flags =", "config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32) # In the", "False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks", "*INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,", "drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir,", "%0.2f for Sentences = %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) *", "padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether", "d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record:", "that uses tf.py_func which is # not TPU compatible. The", "len(features) # This is for demo purposes and does NOT", "end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name, bert_config=bert_config,", "0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training with TF", "predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length,", "= %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms)", "= max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100", "\"do_lower_case\", True, \"Whether to lower case the input text. Should", "d = tf.data.Dataset.from_tensor_slices({ \"input_ids\": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"input_mask\":", "(sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if", "Average (sentences/sec) with overhead = %0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec)", "tokenization import tensorflow as tf import horovod.tensorflow as hvd import", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name ==", "count before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT", "= \"\" if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\"", "= (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg = np.mean(time_list) cf_50", "fp16 to enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(", "processing will be printed. \" \"A number of warnings are", "predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\",", "tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=probabilities) return output_spec return", "* global_batch_size * 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count -", "sets. We do # not use Dataset.from_generator() because that uses", "if task_name == \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP,", "time_list.sort() # Removing outliers (init/warmup) in throughput computation. predict_time_wo_overhead =", "total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec", "tf.data.TFRecordDataset(input_file) if is_training: if hvd is not None: d =", "A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to", "else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1) if", "mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec(", "= create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings)", "Num examples = %d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\",", "= tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if", "hvd.size() remainder = len(train_examples) % hvd.size() if hvd.rank() < remainder:", "training to perform linear learning rate warmup for. \" \"E.g.,", "import modeling import optimization import tokenization import tensorflow as tf", "is # not TPU compatible. The right way to load", "to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name =", "= None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples =", "tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", predict_time_elapsed,", "an `input_fn` closure to be passed to Estimator.\"\"\" all_input_ids =", "predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences =", "tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels],", "= \", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\",", "import set_affinity import utils.dllogger_class from dllogger import Verbosity from utils.create_glue_data", "var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.TRAIN:", "return frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps,", "num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure", "(total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask,", "from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph,", "output directory where the model checkpoints will be written.\") ##", "lower case the input text. Should be True for uncased", "with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name,", "pre-trained BERT model. \" \"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\",", "use_one_hot_embeddings, hvd=None): \"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels,", "FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0), loss_scaler) eval_metric_ops", "Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn =", "parallel reading and shuffling. # For eval, we want no", "before gradient update\" \"Global batch size = num_accumulation_steps * train_batch_size\")", "return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if", "rewrite if fp16 to enable graph rewrite if FLAGS.amp: dummy_op", "predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False,", "input function.\"\"\" # For training, we want a lot of", "FP * FN) / ((TP + FP) * (TP +", "Time = %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count *", "make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation", "Google AI Language Team Authors. # # Licensed under the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 ) frozen_graph = converter.convert() print('Total", "%d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\",", "/ eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences", "keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias,", "\"fp32\") tf.compat.v1.logging.info(\"Latency Confidence Level 50 (ms) = %0.2f\", cf_50 *", "= tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\":", "dllogger import Verbosity from utils.create_glue_data import * import numpy as", "frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph", "hvd.size() master_process = (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list", "max_workspace_size_bytes=(4096 << 20) - 1000, precision_mode = \"FP16\" if FLAGS.amp", "= 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save", "be passed to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64),", "enable graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op =", "is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification", "vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size =", "results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line =", "Apache License, Version 2.0 (the \"License\"); # you may not", "20) - 1000, precision_mode = \"FP16\" if FLAGS.amp else \"FP32\",", "Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data dir. Should", "modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"**** Trainable Variables ****\")", "n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\")", "either express or implied. # See the License for the", "file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure", "estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before gradient", "hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss,", "[] all_input_mask = [] all_segment_ids = [] all_label_ids = []", "'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\":", "FP) * (TP + FN) * (TN + FP) *", "output_spec (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids,", "to run the model in inference mode on the test", "does NOT scale to large data sets. We do #", "%0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ ==", "Language Team Authors. # # Licensed under the Apache License,", "(TP * TN - FP * FN) / ((TP +", "{}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None", "max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead", "division from __future__ import print_function import collections import csv import", "\"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How", "to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total number of training epochs", "*INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s,", "len(train_examples) / global_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)", "num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint", "\", *INIT_FROM_CKPT*\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name,", "shorter \" \"than this will be padded.\") flags.DEFINE_bool(\"do_train\", False, \"Whether", "flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\",", "hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed = time.time()", "* 1)]) ss_sentences_per_second = num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\")", "a record to a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features)", "use Dataset.from_generator() because that uses tf.py_func which is # not", "node count before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node))", "model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32)", "tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key", "use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} if init_checkpoint and", "loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() #", "model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings, hvd=None): \"\"\"Returns", "\"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in", "FLAGS.do_predict: raise ValueError( \"At least one of `do_train`, `do_eval` or", "d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path)", "per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids,", "\"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in", "\"This specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of", "gradient update\" \"Global batch size = num_accumulation_steps * train_batch_size\") flags.DEFINE_bool(\"amp\",", "tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions)", "# For training, we want a lot of parallel reading", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "*****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join(", "processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer,", "\"Whether to run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\",", "len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder = False", "data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") if __name__ == \"__main__\": flags.mark_flag_as_required(\"data_dir\") flags.mark_flag_as_required(\"task_name\")", "accuracy, \"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy(", "print('Converting graph using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt", "\"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The config json file", "tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100 * 1000)", "not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict: raise ValueError(", "logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\":", "output_line = \"\\t\".join( str(class_probability) for class_probability in prediction) + \"\\n\"", "on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for", "* 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg", "\"At least one of `do_train`, `do_eval` or `do_predict' must be", "tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise", "\"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in", "\"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None,", "hvd.init() processors = { \"cola\": ColaProcessor, \"mnli\": MnliProcessor, \"mrpc\": MrpcProcessor,", "for. \" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000,", "tf.argmax(logits, axis=-1, output_type=tf.int32) if task_name == \"cola\": FN, FN_op =", "len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp'])) with", "a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder,", "session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else", "file_based_input_fn_builder( input_file=predict_file, batch_size=FLAGS.predict_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) predict_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time", "%s\" % (name, features[name].shape)) input_ids = features[\"input_ids\"] input_mask = features[\"input_mask\"]", "0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) *", "for cased models.\") flags.DEFINE_integer( \"max_seq_length\", 128, \"The maximum total input", "accumulation steps before gradient update\" \"Global batch size = num_accumulation_steps", "start_index + num_examples_per_rank + 1 else: start_index = hvd.rank() *", "not use Dataset.from_generator() because that uses tf.py_func which is #", "rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\",", "getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps", "for Estimator.\"\"\" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument", "%s\" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer", "for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference", "tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else \"fp32\") tf.compat.v1.logging.info(\"Latency Confidence", "%d\", len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num", "train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0", "FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if", "max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 =", "1, \"Number of accumulation steps before gradient update\" \"Global batch", "= d.shard(hvd.size(), hvd.rank()) d = d.repeat() d = d.shuffle(buffer_size=100) d", "frozen_graph def model_fn_builder(task_name, bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_one_hot_embeddings,", "\"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size", "= t return example def input_fn(): \"\"\"The actual input function.\"\"\"", "= os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict", "= os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file) tf.compat.v1.logging.info(\"***** Running", "list(example.keys()): t = example[name] if t.dtype == tf.int64: t =", "predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP *", "of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\", 0.1, \"Proportion of", "metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return", "= %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\",", "you want to use the token-level output, use model.get_sequence_output() #", "{\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy(", "Dataset.from_generator() because that uses tf.py_func which is # not TPU", "%d hvd.rank() = %d\", hvd.size(), hvd.rank()) global_batch_size = FLAGS.train_batch_size *", "\"\\n\" writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list", "metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else:", "d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return input_fn def main(_):", "os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results", "= %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms)", "tf.compat.v1.logging.info(\"***** Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\"", "use this file except in compliance with the License. #", "d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d return", "# not use Dataset.from_generator() because that uses tf.py_func which is", "to Estimator.\"\"\" name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length],", "flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The input data", "seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if", "if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0)) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not", "vocabulary file that the BERT model was trained on.\") flags.DEFINE_string(", "flags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\",", "TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports", "+ num_examples_per_rank + 1 else: start_index = hvd.rank() * num_examples_per_rank", "other data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None,", "from a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to", "def model_fn(features, labels, mode, params): # pylint: disable=unused-argument \"\"\"The `model_fn`", "size for training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\")", "t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return", "if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable Variables ****\") for var in tvars:", "FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None,", "remainder end_index = start_index + (num_examples_per_rank) model_fn = model_fn_builder( task_name=task_name,", "import csv import os import modeling import optimization import tokenization", "but the TPU only supports tf.int32. # So cast all", "else hvd) train_start_time = time.time() estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=training_hooks) train_time_elapsed =", "only trained up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings))", "FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int(", "< remainder: start_index = hvd.rank() * (num_examples_per_rank+1) end_index = start_index", "(key, str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file", "with tf.io.gfile.GFile(output_predict_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Predict results *****\") for", "= tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting graph using", "\"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How", "\"Sequences longer than this will be truncated, and sequences shorter", "to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The vocabulary file that the BERT", "adam or lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from", "TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN -", "we are doing a simple classification task on the entire", "estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps to make in each", "len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index = hvd.rank()", "cf_90 = max(time_list[:int(len(time_list) * 0.90)]) cf_95 = max(time_list[:int(len(time_list) * 0.95)])", "len(train_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps", "*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size", "input_fn_builder(features, batch_size, seq_length, is_training, drop_remainder, hvd=None): \"\"\"Creates an `input_fn` closure", "input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging = utils.dllogger_class.dllogger_class(FLAGS.dllog_path) if FLAGS.horovod:", "output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess:", "(init/warmup) in throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences", "set\") tf.compat.v1.logging.info(\"Batch size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\",", "logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits')", "in compliance with the License. # You may obtain a", "to large data sets. We do # not use Dataset.from_generator()", "tf.compat.v1.logging.info(\"Latency Confidence Level 99 (ms) = %0.2f\", cf_99 * 1000)", "software # distributed under the License is distributed on an", "shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\":", "num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead = %0.2f", "tf.compat.v1.logging.info(\"-----------------------------\") if FLAGS.do_eval and master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file =", "as tf import horovod.tensorflow as hvd import time from utils.utils", "ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\", cf_95", "`model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode, params): #", ".tsv files (or other data files) \" \"for the task.\")", "seq_length], dtype=tf.int32), \"input_mask\": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant(", "num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL set\") tf.compat.v1.logging.info(\"Batch size =", "'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities}", "init_checkpoint and (hvd is None or hvd.rank() == 0): (assignment_map,", ") = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) if FLAGS.verbose_logging: tf.compat.v1.logging.info(\"**** Trainable", "mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps,", "sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\" % (name,", "ValueError( \"Cannot use sequence length %d because the BERT model", "ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 /", "%d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec)", "test set.\") flags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\") flags.DEFINE_integer(\"eval_batch_size\",", "predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O Overhead =", "import collections import csv import os import modeling import optimization", "tf.Example only supports tf.int64, but the TPU only supports tf.int32.", "model in inference mode on the test set.\") flags.DEFINE_integer(\"train_batch_size\", 32,", "global_batch_size * 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training", "= False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder)", "\"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer: tf.compat.v1.logging.info(\"***** Eval results *****\")", "shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is not None:", "FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / global_batch_size", "loss, } tf.compat.v1.logging.info(\"*** Features ***\") tf.compat.v1.logging.info(\"*** Features ***\") for name", "\", *INIT_FROM_CKPT*\" else: init_string = \", *NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name =", "input sequence length after WordPiece tokenization. \" \"Sequences longer than", "= [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id)", "size = %d\", FLAGS.train_batch_size) tf.compat.v1.logging.info(\" Num steps = %d\", num_train_steps)", "key, str(result[key])) writer.write(\"%s = %s\\n\" % (key, str(result[key]))) if FLAGS.do_predict", "True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as", "label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training *****\") tf.compat.v1.logging.info(\" Num", "verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as", "int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples) tmp_filenames", "training_hooks = [] global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps hvd_rank =", "seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result", "log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss,", "tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op =", "\"bert_config_file\", None, \"The config json file corresponding to the pre-trained", "tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length],", "* 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) = %0.2f\", cf_100", "tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels,", "model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the task to", "master_process = (hvd.rank() == 0) hvd_rank = hvd.rank() config.gpu_options.visible_device_list =", "`input_fn` closure to be passed to Estimator.\"\"\" name_to_features = {", "FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\"", "tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs =", "as trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20)", "class_probability in prediction) + \"\\n\" writer.write(output_line) predict_time_elapsed = time.time() -", "with the License. # You may obtain a copy of", "= tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1,", "= len(train_examples) % hvd.size() if hvd.rank() < remainder: start_index =", "processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer, predict_file)", "if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info('", "FLAGS.num_accumulation_steps hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU", "segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model =", "features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def input_fn(): \"\"\"The actual input", "master_process else None, session_config=config, save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps", "= FLAGS.task_name.lower() if task_name not in processors: raise ValueError(\"Task not", "cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0", "= predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup) in throughput computation.", "`do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length >", "prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for", "was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory where", "express or implied. # See the License for the specific", "- train_start_time train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size", "in sorted(result.keys()): dllogging.logger.log(step=(), data={key: float(result[key])}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\" %s = %s\",", "except in compliance with the License. # You may obtain", "d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size,", "name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif task_name == \"mrpc\": accuracy", "for predict.\") flags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")", "from utils.create_glue_data import * import numpy as np import tf_metrics", "if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)", "tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average", "* 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.predict_batch_size avg", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "using TensorFlow-TensorRT...') from tensorflow.python.compiler.tensorrt import trt_convert as trt converter =", "\"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False,", "be truncated, and sequences shorter \" \"than this will be", "initial learning rate for Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use", "FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples = None", "t = tf.to_int32(t) example[name] = t return example def input_fn():", "train_time_wo_overhead = training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0", "} if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:", "lamb\") flags.DEFINE_string( \"init_checkpoint\", None, \"Initial checkpoint (usually from a pre-trained", "if is_training: if hvd is not None: d = d.shard(hvd.size(),", "CONDITIONS OF ANY KIND, either express or implied. # See", "3.0, \"Total number of training epochs to perform.\") flags.DEFINE_float( \"warmup_proportion\",", "parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training: if", "\"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([], tf.int64), }", "tf.estimator.ModeKeys.EVAL: eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode,", "(FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in", "because the BERT model \" \"was only trained up to", "name = %s, shape = %s%s\", var.name, var.shape, init_string) output_spec", "== tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op() # Need to call mixed", "training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps", "predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions) TP, TP_op = tf.metrics.true_positives(labels=label_ids,", "bert_config=bert_config, num_labels=len(label_list), init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate if not FLAGS.horovod else FLAGS.learning_rate *", "shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32,", "* log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss,", "FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\"", "eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)", "'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT:", "The right way to load data is with TFRecordReader. d", "logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities = tf.nn.softmax(logits, axis=-1, name='cls_probabilities')", "tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP * TN - FP *", "loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op = tf.no_op() # Need to call", "\"output_dir\", None, \"The output directory where the model checkpoints will", "keep_checkpoint_max=1) if master_process: tf.compat.v1.logging.info(\"***** Configuaration *****\") for key in FLAGS.__flags.keys():", "total input sequence length after WordPiece tokenization. \" \"Sequences longer", "All rights reserved. # Copyright 2018 The Google AI Language", "params): # pylint: disable=unused-argument \"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss,", "(ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 99", "= d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features),", "will be truncated, and sequences shorter \" \"than this will", "* 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list) cf_50 = max(time_list[:int(len(time_list)", "size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\")", "num_labels, use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids,", "training.\") flags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev", "label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process =", "(ms) = %0.2f\", cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95", "= \"FP16\" if FLAGS.amp else \"FP32\", minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000 )", "shape = %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(),", "Time W/O Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead,", "Inference Time = %0.2f for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count", "trt converter = trt.TrtGraphConverter( input_graph_def=frozen_graph, nodes_blacklist=output_node_names, max_workspace_size_bytes=(4096 << 20) -", "num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size avg = np.mean(time_list)", "output_spec = None if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer(", "= tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids') label_ids", "not is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings,", "use_one_hot_embeddings, init_checkpoint) (total_loss, per_example_loss, logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask,", "\"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: if hvd is", "not in processors: raise ValueError(\"Task not found: %s\" % (task_name))", "`model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits,", "= %s, shape = %s%s\", var.name, var.shape, init_string) output_spec =", "% (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not", "compute_type=tf.float32) # In the demo, we are doing a simple", "cf_95 = max(time_list[:int(len(time_list) * 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)])", "tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(eval_examples))", "to enable graph rewrite if FLAGS.amp: dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite( optimization.LAMBOptimizer(learning_rate=0.0))", "if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir,", "not used by this file but is still used by", "is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits", "tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), })", "def _decode_record(record, name_to_features): \"\"\"Decodes a record to a TensorFlow example.\"\"\"", "all_label_ids = [] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids)", "W/O Overhead = %0.2f for Sentences = %d\", eval_time_wo_overhead, num_sentences)", "runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the warnings", "# segment. # # If you want to use the", "in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\") train_examples =", "= 0 end_index = len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if", "= time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing", "name in sorted(features.keys()): tf.compat.v1.logging.info(\" name = %s, shape = %s\"", "tf.compat.v1.logging.info(\" %s = %s\", key, str(result[key])) writer.write(\"%s = %s\\n\" %", "computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) *", "hvd.rank() == 0): (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint,", "\" \"was only trained up to sequence length %d\" %", "predictions=predictions) MCC = (TP * TN - FP * FN)", "tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString()) return frozen_graph def model_fn_builder(task_name, bert_config,", "the Colab and # people who depend on it. def", "= int(num_train_steps * FLAGS.warmup_proportion) start_index = 0 end_index = len(train_examples)", "master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time = %0.2f for Sentences =", "%d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time W/O Overhead", "'loss/cls_per_example_loss:0', 'loss/cls_logits:0', 'loss/cls_probabilities:0'], name='') if mode == tf.estimator.ModeKeys.PREDICT: predictions =", "input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model", "axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels,", "reading and shuffling. # For eval, we want no shuffling", "if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config =", "writer.write(output_line) predict_time_elapsed = time.time() - predict_start_time time_list = predict_hooks[-1].time_list time_list.sort()", "= %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on TEST SET\")", "for demo purposes and does NOT scale to large data", "else: dummy_op = tf.no_op() # Need to call mixed precision", "}) if is_training: if hvd is not None: d =", "CORPORATION. All rights reserved. # Copyright 2018 The Google AI", "bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors:", "initialized_variable_names = {} if init_checkpoint and (hvd is None or", "% (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer =", "logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config =", "labels=label_ids, predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) f1 = tf_metrics.f1(labels=label_ids, predictions=predictions, num_classes=2,", "= %d\", FLAGS.predict_batch_size) predict_drop_remainder = False predict_input_fn = file_based_input_fn_builder( input_file=predict_file,", "num_labels, use_one_hot_embeddings): \"\"\"Creates a classification model.\"\"\" model = modeling.BertModel( config=bert_config,", "== \"cola\": FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op =", "a TensorFlow example.\"\"\" example = tf.parse_single_example(record, name_to_features) # tf.Example only", "per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint): tf_config", "learning rate warmup for. \" \"E.g., 0.1 = 10% of", "modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( \"Cannot use sequence", "trained up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir)", "None, \"The config json file corresponding to the pre-trained BERT", "(sentences/sec) = %0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file", "axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss') return (loss, per_example_loss, logits,", "eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples, label_list,", "supports tf.int32. # So cast all int64 to int32. for", "True for uncased \" \"models and False for cased models.\")", "flags.DEFINE_bool( \"do_predict\", False, \"Whether to run the model in inference", "logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) else: dummy_op =", "init_string = \"\" if var.name in initialized_variable_names: init_string = \",", "= %s%s\", var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names)", "uses tf.py_func which is # not TPU compatible. The right", "outliers (init/warmup) in throughput computation. eval_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)])", "the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import absolute_import from", "* 0.95)]) cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list)", "Trainable Variables ****\") for var in tvars: init_string = \"\"", "specifies the model architecture.\") flags.DEFINE_string(\"task_name\", None, \"The name of the", "# # If you want to use the token-level output,", "training_hooks[-1].total_time avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed", "FN, FN_op = tf.metrics.false_negatives(labels=label_ids, predictions=predictions) FP, FP_op = tf.metrics.false_positives(labels=label_ids, predictions=predictions)", "%d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size) predict_drop_remainder =", "train_batch_size\") flags.DEFINE_bool(\"amp\", True, \"Whether to enable AMP ops. When false,", "call mixed precision graph rewrite if fp16 to enable graph", "str(result[key]))) if FLAGS.do_predict and master_process: predict_examples = processor.get_test_examples(FLAGS.data_dir) predict_file =", "Training Time W/O Overhead = %0.2f for Sentences = %d\",", "if var.name in initialized_variable_names: init_string = \", *INIT_FROM_CKPT*\" else: init_string", "want no shuffling and parallel reading doesn't matter. d =", "name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)", "flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\") flags.DEFINE_string(", "FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( \"data_dir\", None, \"The", "= hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank +", "%0.2f\", cf_99 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 100 (ms) =", "supports tf.int64, but the TPU only supports tf.int32. # So", "logits, probabilities) = tf.import_graph_def(trt_graph, input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids, 'label_ids':label_ids}, return_elements=['loss/cls_loss:0', 'loss/cls_per_example_loss:0',", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "name_to_features = { \"input_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\":", "batch_size=FLAGS.eval_batch_size, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time()", "normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None):", "where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type :", "true, all of the warnings related to data processing will", "and parallel reading doesn't matter. d = tf.data.TFRecordDataset(input_file) if is_training:", "FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss, train_op=train_op) elif mode", "* 1.0 / train_time_elapsed ss_sentences_per_second = (training_hooks[-1].count - training_hooks[-1].skipped) *", "not FLAGS.horovod else FLAGS.learning_rate * hvd.size(), num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None", "each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of accumulation steps before", "* TN - FP * FN) / ((TP + FP)", "\"\"\"The `model_fn` for Estimator.\"\"\" def metric_fn(per_example_loss, label_ids, logits): predictions =", "the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss", "tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions) MCC = (TP", "Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary", "tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) master_process = True training_hooks = [] global_batch_size", "'input_ids') input_mask = tf.placeholder(tf.int32, shape, 'input_mask') segment_ids = tf.placeholder(tf.int32, shape,", "and # people who depend on it. def input_fn_builder(features, batch_size,", "%d\", len(eval_examples)) tf.compat.v1.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size) eval_drop_remainder =", "sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list) * 0.8)) * FLAGS.eval_batch_size", "on A100 and FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether", "Running prediction*****\") tf.compat.v1.logging.info(\" Num examples = %d\", len(predict_examples)) tf.compat.v1.logging.info(\" Batch", "if fp16 to enable graph rewrite if FLAGS.amp: dummy_op =", "= tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops =", "hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02))", "- predict_start_time time_list = predict_hooks[-1].time_list time_list.sort() # Removing outliers (init/warmup)", "eval_time_elapsed = time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() #", "\"/results/bert_dllog.json\", \"filename where dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer", "return (loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings,", "tf.no_op() # Need to call mixed precision graph rewrite if", "* FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0) hvd_rank", "actual input function.\"\"\" # For training, we want a lot", "Version 2.0 (the \"License\"); # you may not use this", "result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time time_list", "95 (ms) = %0.2f\", cf_95 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level", "if task_name not in processors: raise ValueError(\"Task not found: %s\"", "import division from __future__ import print_function import collections import csv", "training.\") flags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8,", "= len(train_examples) // hvd.size() remainder = len(train_examples) % hvd.size() if", "num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank) model_fn =", "to run eval on the dev set.\") flags.DEFINE_bool( \"do_predict\", False,", "__future__ import absolute_import from __future__ import division from __future__ import", "writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or", "a lot of parallel reading and shuffling. # For eval,", "input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings):", "to int32. for name in list(example.keys()): t = example[name] if", "model was trained on.\") flags.DEFINE_string( \"output_dir\", None, \"The output directory", "None num_train_steps = None num_warmup_steps = None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps,", "multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the", "size = %d\", FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Sequence Length = %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision", "batch_size=FLAGS.train_batch_size, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True, hvd=None if not FLAGS.horovod else hvd)", "= %d\", FLAGS.max_seq_length) tf.compat.v1.logging.info(\"Precision = %s\", \"fp16\" if FLAGS.amp else", "FP32 on V100 GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA", "to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\", 1000, \"How many steps", "tf.compat.v1.logging.info(\"Total Inference Time = %0.2f for Sentences = %d\", eval_time_elapsed,", "by applicable law or agreed to in writing, software #", "mode=mode, loss=total_loss, eval_metric_ops=eval_metric_ops) return output_spec (total_loss, per_example_loss, logits, probabilities) =", "FLAGS.do_train: file_based_convert_examples_to_features( train_examples[start_index:end_index], label_list, FLAGS.max_seq_length, tokenizer, tmp_filenames[hvd_rank]) tf.compat.v1.logging.info(\"***** Running training", "%0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics", "\"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer())", "up to sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name", "cf_50 = max(time_list[:int(len(time_list) * 0.50)]) cf_90 = max(time_list[:int(len(time_list) * 0.90)])", "uncased \" \"models and False for cased models.\") flags.DEFINE_integer( \"max_seq_length\",", "\"mrpc\": MrpcProcessor, \"xnli\": XnliProcessor, } if not FLAGS.do_train and not", "flags.DEFINE_bool( \"verbose_logging\", False, \"If true, all of the warnings related", "1000, \"How often to save the model checkpoint.\") flags.DEFINE_integer(\"display_loss_steps\", 10,", "TP, TP_op = tf.metrics.true_positives(labels=label_ids, predictions=predictions) TN, TN_op = tf.metrics.true_negatives(labels=label_ids, predictions=predictions)", "is None or hvd.rank() == 0): (assignment_map, initialized_variable_names ) =", "GPUS.\") flags.DEFINE_bool(\"use_xla\", True, \"Whether to enable XLA JIT compilation.\") flags.DEFINE_bool(\"horovod\",", "W/O Overhead = %0.2f for Sentences = %d\", predict_time_wo_overhead, num_sentences)", "graph rewrite if FLAGS.amp: loss_scaler = tf.train.experimental.FixedLossScale(1) dummy_op = tf.train.experimental.enable_mixed_precision_graph_rewrite(", "\"\"\"Returns `model_fn` closure for Estimator.\"\"\" def model_fn(features, labels, mode, params):", "{} if init_checkpoint and (hvd is None or hvd.rank() ==", "size = %d\", FLAGS.eval_batch_size) eval_drop_remainder = False eval_input_fn = file_based_input_fn_builder(", "for Sentences = %d\", predict_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on", "import os import modeling import optimization import tokenization import tensorflow", "model.get_sequence_output() # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights", "if mode == tf.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps,", "flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the input text.", "for Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference", "'label_ids') create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars", "master_process else None, save_summary_steps=FLAGS.save_checkpoints_steps if master_process else None, log_step_count_steps=FLAGS.display_loss_steps, keep_checkpoint_max=1)", "= %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total Inference Time W/O", "max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second =", "= (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead", "cf_99 = max(time_list[:int(len(time_list) * 0.99)]) cf_100 = max(time_list[:int(len(time_list) * 1)])", "str(hvd.local_rank()) set_affinity(hvd.local_rank()) if hvd.size() > 1: training_hooks.append(hvd.BroadcastGlobalVariablesHook(0)) if FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level", "frozen_graph = converter.convert() print('Total node count before and after TF-TRT", "(assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\") tf.compat.v1.logging.info(\"****", "dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with", "in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False): output_line = \"\\t\".join( str(class_probability) for class_probability", "drop_remainder=drop_remainder) return d return input_fn def main(_): setup_xla_flags() tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) dllogging", "import numpy as np import tf_metrics flags = tf.flags FLAGS", "cf_90 * 1000) tf.compat.v1.logging.info(\"Latency Confidence Level 95 (ms) = %0.2f\",", "%0.2f for Sentences = %d\", predict_time_elapsed, predict_hooks[-1].count * FLAGS.predict_batch_size) tf.compat.v1.logging.info(\"Total", "case the input text. Should be True for uncased \"", "if mode == tf.estimator.ModeKeys.PREDICT: predictions = {\"probabilities\": probabilities} output_spec =", "hvd_rank = 0 config = tf.compat.v1.ConfigProto() if FLAGS.horovod: tf.compat.v1.logging.info(\"Multi-GPU training", "tf.compat.v1.logging.info(\"**************************\") train_examples = None num_train_steps = None num_warmup_steps = None", "[LogEvalRunHook(FLAGS.predict_batch_size)] predict_start_time = time.time() output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\") with tf.io.gfile.GFile(output_predict_file,", "= d.repeat() d = d.shuffle(buffer_size=100) d = d.apply( tf.contrib.data.map_and_batch( lambda", "linear learning rate warmup for. \" \"E.g., 0.1 = 10%", "input function.\"\"\" num_examples = len(features) # This is for demo", "applicable law or agreed to in writing, software # distributed", "len(train_examples) tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir,", "100 (ms) = %0.2f\", cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms)", "\"eval_f1\": f1, \"eval_loss\": loss, } else: accuracy = tf.metrics.accuracy( labels=label_ids,", "= tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the", "= time.time() - eval_start_time time_list = eval_hooks[-1].time_list time_list.sort() # Removing", "Sentences = %d\", eval_time_wo_overhead, num_sentences) tf.compat.v1.logging.info(\"Summary Inference Statistics on EVAL", "= tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias, name='cls_logits') probabilities", "tf.Session(config=tf_config) as tf_sess: input_ids = tf.placeholder(tf.int32, shape, 'input_ids') input_mask =", "\"\"\"Creates an `input_fn` closure to be passed to Estimator.\"\"\" all_input_ids", "= num_sentences * 1.0 / predict_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time", "tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf_sess.run(tf.global_variables_initializer()) print(\"LOADED!\")", "limitations under the License. \"\"\"BERT finetuning runner.\"\"\" from __future__ import", "WordPiece tokenization. \" \"Sequences longer than this will be truncated,", "tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record\")] if FLAGS.horovod: tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i))", "max(time_list[:int(len(time_list) * 1)]) ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead", "to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam or lamb\")", "model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower case the input", "TN_op, TP_op, FP_op, tf.identity(MCC, name=\"MCC\")) return {\"MCC\": (MCC, MCC_op)} elif", "%0.2f\", avg_sentences_per_second) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) = %0.2f\", ss_sentences_per_second) tf.compat.v1.logging.info(\"-----------------------------\") if", "2019 NVIDIA CORPORATION. All rights reserved. # Copyright 2018 The", "= output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias", "tmp_filenames = [os.path.join(FLAGS.output_dir, \"train.tf_record{}\".format(i)) for i in range(hvd.size())] num_examples_per_rank =", "eval, we want no shuffling and parallel reading doesn't matter.", "= num_sentences * 1.0 / eval_time_wo_overhead tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Inference Time", "model_fn # This function is not used by this file", "Authors. # # Licensed under the Apache License, Version 2.0", "\" \"E.g., 0.1 = 10% of training.\") flags.DEFINE_integer(\"save_checkpoints_steps\", 1000, \"How", "master_process: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\") file_based_convert_examples_to_features( eval_examples,", "are doing a simple classification task on the entire #", "is_training and FLAGS.use_trt: trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, num_labels, use_one_hot_embeddings, init_checkpoint)", "\"Proportion of training to perform linear learning rate warmup for.", "elif task_name == \"mrpc\": accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions) loss", "cf_100 * 1000) tf.compat.v1.logging.info(\"Latency Average (ms) = %0.2f\", avg *", "\"The vocabulary file that the BERT model was trained on.\")", "# You may obtain a copy of the License at", "from utils.gpu_affinity import set_affinity import utils.dllogger_class from dllogger import Verbosity", "to make in each estimator call.\") flags.DEFINE_integer(\"num_accumulation_steps\", 1, \"Number of", "create_model(bert_config, False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars =", "= True output_node_names = ['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config)", "(TN + FN)) ** 0.5 MCC_op = tf.group(FN_op, TN_op, TP_op,", "sequence length %d\" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.io.gfile.makedirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower()", "Adam.\") flags.DEFINE_bool(\"use_trt\", False, \"Whether to use TF-TRT\") flags.DEFINE_float(\"num_train_epochs\", 3.0, \"Total", "input_mask = features[\"input_mask\"] segment_ids = features[\"segment_ids\"] label_ids = features[\"label_ids\"] is_training", "Should be True for uncased \" \"models and False for", "tokenizer, eval_file) tf.compat.v1.logging.info(\"***** Running evaluation *****\") tf.compat.v1.logging.info(\" Num examples =", "Sentences = %d\", eval_time_elapsed, eval_hooks[-1].count * FLAGS.eval_batch_size) tf.compat.v1.logging.info(\"Total Inference Time", "var.name, var.shape, init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes =", "mode=mode, loss=total_loss, train_op=train_op) elif mode == tf.estimator.ModeKeys.EVAL: dummy_op = tf.no_op()", "tf.enable_resource_variables() run_config = tf.estimator.RunConfig( model_dir=FLAGS.output_dir if master_process else None, session_config=config,", "`do_train`, `do_eval` or `do_predict' must be True.\") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)", "I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer,", "(ms) = %0.2f\", avg * 1000) tf.compat.v1.logging.info(\"Throughput Average (sentences/sec) =", "flags.DEFINE_integer(\"display_loss_steps\", 10, \"How often to print loss from estimator\") flags.DEFINE_integer(\"iterations_per_loop\",", "= %d\", train_time_wo_overhead, (training_hooks[-1].count - training_hooks[-1].skipped) * global_batch_size) tf.compat.v1.logging.info(\"Throughput Average", "Sentences = %d\", train_time_elapsed, num_train_steps * global_batch_size) tf.compat.v1.logging.info(\"Total Training Time", "tf.io.FixedLenFeature([seq_length], tf.int64), \"input_mask\": tf.io.FixedLenFeature([seq_length], tf.int64), \"segment_ids\": tf.io.FixedLenFeature([seq_length], tf.int64), \"label_ids\": tf.io.FixedLenFeature([],", "use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator(", "use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\", False, \"If true,", "tf.compat.v1.logging.info(\"***** Predict results *****\") for prediction in estimator.predict(input_fn=predict_input_fn, hooks=predict_hooks, yield_single_examples=False):", "(loss, per_example_loss, logits, probabilities) def get_frozen_tftrt_model(bert_config, shape, num_labels, use_one_hot_embeddings, init_checkpoint):", "use_one_hot_embeddings) tvars = tf.trainable_variables() (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint,", "for eval.\") flags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\") flags.DEFINE_float(\"learning_rate\",", "for a normal SQuAD evaluation.\") def file_based_input_fn_builder(input_file, batch_size, seq_length, is_training,", "* FN) / ((TP + FP) * (TP + FN)", "\"The name of the task to train.\") flags.DEFINE_string(\"vocab_file\", None, \"The", "time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed = time.time() - eval_start_time", "\"verbose_logging\", False, \"If true, all of the warnings related to", "init_string) frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess, tf_sess.graph.as_graph_def(), output_node_names) num_nodes = len(frozen_graph.node) print('Converting", "import tf_metrics flags = tf.flags FLAGS = flags.FLAGS ## Required", "if str(n.op) == 'TRTEngineOp'])) with tf.io.gfile.GFile(\"frozen_modelTRT.pb\", \"wb\") as f: f.write(frozen_graph.SerializeToString())", "= [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn, hooks=eval_hooks) eval_time_elapsed", "= tf.nn.softmax(logits, axis=-1, name='cls_probabilities') log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels =", "FLAGS.train_batch_size * FLAGS.num_accumulation_steps * hvd.size() master_process = (hvd.rank() == 0)", "tf.compat.v1.logging.info(\"*** Features ***\") for name in sorted(features.keys()): tf.compat.v1.logging.info(\" name =", "['loss/cls_loss', 'loss/cls_per_example_loss', 'loss/cls_logits', 'loss/cls_probabilities'] with tf.Session(config=tf_config) as tf_sess: input_ids =", "eval_metric_ops = metric_fn(per_example_loss, label_ids, logits) output_spec = tf.estimator.EstimatorSpec( mode=mode, loss=total_loss,", "((TP + FP) * (TP + FN) * (TN +", "*NOTTTTTTTTTTTTTTTTTTTTT\" tf.compat.v1.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,", "model \" \"was only trained up to sequence length %d\"", "shuffling. # For eval, we want no shuffling and parallel", "least one of `do_train`, `do_eval` or `do_predict' must be True.\")", "TF Horovod\") tf.compat.v1.logging.info(\"hvd.size() = %d hvd.rank() = %d\", hvd.size(), hvd.rank())", "import Verbosity from utils.create_glue_data import * import numpy as np", "hvd.rank() * (num_examples_per_rank+1) end_index = start_index + num_examples_per_rank + 1", "predictions = {\"probabilities\": probabilities} output_spec = tf.estimator.EstimatorSpec( mode=mode, predictions=predictions) elif", "data files) \" \"for the task.\") flags.DEFINE_string( \"bert_config_file\", None, \"The", "if fp16 to enable graph rewrite if FLAGS.amp: loss_scaler =", "a pre-trained BERT model).\") flags.DEFINE_bool( \"do_lower_case\", True, \"Whether to lower", "= model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( \"output_weights\", [num_labels,", "name in list(example.keys()): t = example[name] if t.dtype == tf.int64:", "t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t)", "\"License\"); # you may not use this file except in", "writer: tf.compat.v1.logging.info(\"***** Eval results *****\") for key in sorted(result.keys()): dllogging.logger.log(step=(),", "# This function is not used by this file but", "drop_remainder=eval_drop_remainder) eval_hooks = [LogEvalRunHook(FLAGS.eval_batch_size)] eval_start_time = time.time() result = estimator.evaluate(input_fn=eval_input_fn,", "False, \"Whether to use Horovod for multi-gpu runs\") flags.DEFINE_bool( \"verbose_logging\",", "dllogger writes to\") flags.DEFINE_string( \"optimizer_type\", \"lamb\", \"Optimizer type : adam", "example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but", "AMP ops. When false, uses TF32 on A100 and FP32", "not FLAGS.horovod else hvd) estimator = tf.estimator.Estimator( model_fn=model_fn, config=run_config) if", "dtype=tf.int32), \"segment_ids\": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), \"label_ids\": tf.constant(all_label_ids, shape=[num_examples],", "None training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps, num_steps_ignore_xla=25)) if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir)", "\"The input data dir. Should contain the .tsv files (or", "horovod.tensorflow as hvd import time from utils.utils import LogEvalRunHook, LogTrainRunHook,", "hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( \"output_bias\", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope(\"loss\"):", "%0.2f\", ss_sentences_per_second) dllogging.logger.log(step=(), data={\"throughput_val\": ss_sentences_per_second}, verbosity=Verbosity.DEFAULT) tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir,", "FLAGS.use_xla: config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1 if FLAGS.amp: tf.enable_resource_variables() run_config = tf.estimator.RunConfig(", "So cast all int64 to int32. for name in list(example.keys()):", "for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key))) tf.compat.v1.logging.info(\"**************************\")", "with tf.variable_scope(\"loss\"): if is_training: # I.e., 0.1 dropout output_layer =", "raise ValueError( \"Cannot use sequence length %d because the BERT", "*****\") for key in FLAGS.__flags.keys(): tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key)))", "(mode == tf.estimator.ModeKeys.TRAIN) if not is_training and FLAGS.use_trt: trt_graph =", "throughput computation. predict_time_wo_overhead = sum(time_list[:int(len(time_list) * 0.8)]) num_sentences = (int(len(time_list)", "* num_examples_per_rank + remainder end_index = start_index + (num_examples_per_rank) model_fn", "False, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables()", "learning_rate, num_train_steps, num_warmup_steps, hvd, False, FLAGS.amp, FLAGS.num_accumulation_steps, FLAGS.optimizer_type) output_spec =", "tf.placeholder(tf.int32, shape, 'segment_ids') label_ids = tf.placeholder(tf.int32, (None), 'label_ids') create_model(bert_config, False,", "= processor.get_test_examples(FLAGS.data_dir) predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\") file_based_convert_examples_to_features(predict_examples, label_list, FLAGS.max_seq_length, tokenizer,", "var in tvars: init_string = \"\" if var.name in initialized_variable_names:", "[] for feature in features: all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mask) all_segment_ids.append(feature.segment_ids) all_label_ids.append(feature.label_id) def", "predictions=predictions) loss = tf.metrics.mean(values=per_example_loss) return { \"eval_accuracy\": accuracy, \"eval_loss\": loss,", "\"xnli\": XnliProcessor, } if not FLAGS.do_train and not FLAGS.do_eval and", "before and after TF-TRT conversion:', num_nodes, '->', len(frozen_graph.node)) print('TRT node", "* 1.0 / train_time_wo_overhead if master_process: tf.compat.v1.logging.info(\"-----------------------------\") tf.compat.v1.logging.info(\"Total Training Time", "tf.compat.v1.logging.info(\"-----------------------------\") output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\") with tf.io.gfile.GFile(output_eval_file, \"w\") as writer:", "drop_remainder=drop_remainder)) return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask,", "= -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss = tf.reduce_mean(per_example_loss, name='cls_loss')", "num_warmup_steps=num_warmup_steps, use_one_hot_embeddings=False, hvd=None if not FLAGS.horovod else hvd) estimator =", "be written.\") ## Other parameters flags.DEFINE_string( \"dllog_path\", \"/results/bert_dllog.json\", \"filename where", "dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1, name='cls_per_example_loss') loss =" ]
[ "no, # profile picture, about me etc of a student", "ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title =", "if request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now()", "entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme)", "HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6,", "= Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme=", "- the rollno of the student required to check if", "request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= {", "the curriculum from database obj - get stdents data from", "Description for the previous event which is to be updated.", "request t - Object of Exam time table to be", "request_sem = request.POST['sem'] except Exception as e: request_batch = \"\"", "request - contains metadata about the requested page @variables: programme", "# user = get_object_or_404(User, username = e.user.username) # s =", "'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' :", "event. to_date - The ending date for the academic caldendar", "'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1']", "student will become # convenor or coconvenor # hDes -", "that holds the designation as a senator students - all", "# @variables: # rollno - rollno of the student to", "the extraInfo objects that holds the designation as a convenor", "return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/')", "print(request.POST['delete']) # data = request.POST['delete'] # d = data.split(\"-\") #", "curriculum from database obj - get stdents data from database", "book - workbook of xlsx file title - formatting variable", "college attendance - all the attendance objects of the students", "of student from file phone_no - details of student from", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if", "the designation object that contains convenor # c - the", "- get stdents data from database ans - Formatted Array", "all the extraInfor objects exam_t - all the exam timetable", "batch - batch form form curriculum - curriculum details form", "about the requested page. @variables: profiles - gets the excel", "sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else: course_list_2", "of student from file batch - details of student from", "application. It checkes the authentication of the user and also", "is a senator # hDes - the holdDesignation object that", "in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name)", "convenor/coconvenor from the position # @param: # request - contains", "student - the student object with the given pk #", "upload the exam timtable of the ongoing semester. @param: request", "sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num =", "output b - temporary variables for final output c -", "HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic profile################## #", "# desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation =", "details of the required user. # \"\"\" # current_user =", "as a dean student - the students as a senator", "a curriculum. It checkes the authentication of the user and", "# if (str(p.course_id) == course): # print(p.course_id) # p.delete() #", "- contains metadata about the requested page. @variables: request_batch -", "from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student,", "Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval", "Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request):", "Dean - the extraInfo objects that holds the designation as", "check if the student is available desig_id - mother's name", "next_curriculum(request): \"\"\" This function is used to decide curriculum for", "Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name =", "Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all()", "specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if", "str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext)", "# p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') #", "about me etc of a student # @param: # request", "academic calender objects context - the datas to be displayed", ":['5','1'] } if request.method == 'POST': try: request_batch = request.POST['batch']", "from file hall_no - details of student from file programme", "Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] }", "== \"POST\": # data = request.POST['delete'] # t = Meeting.objects.get(id=data)", "return response @login_required def add_new_profile (request): \"\"\" To add details", "new extrainfo object created in database stud_data - new student", "\"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) #", "about the requested page @variables: sem - get current semester", "next_sem_courses - the data of next semester courses courses -", "to variable data k -temporary array to add data to", "Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE #", "request_sem = \"\" #for checking if the user has searched", ":['10','2'] } examTtForm = ExamTimetableForm() if request.method == 'POST' and", "required to check if the student is available # desig_id", "temporary variables z - temporary variables for final output b", "= year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if", "reg - create registeration object in registeration table \"\"\" if", "i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department)", "added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if", "student from file specialization - details of student from file", "# # ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): #", "# curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades", "variables for final output c - temporary variables for final", "= HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = '", "# course = d[2] # sem = int(d[3]) # if", "it to an array. # sem - Get the object", "= batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses =", "user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme =", "# result - the data that contains where the student", "= batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email,", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request,", "request.method == 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in", "context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the exam", "forms and the append it to an array. # sem", "ongoing semester. @param: request - contains metadata about the requested", "a senator students - all the objects in the Student", "- formatting variable of subtitle the workbook normaltext - formatting", "for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code,", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm hone", "academic calendar event. c = object to save new event", "- temporary varibles faculty - details of faculty of data", "programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name =", "course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch", "new upcoming students in the database.User must be logged in", "profile information like hall no, room no, # profile picture,", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if", "context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request,", "obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for", "return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch')", "student from file address - details of student from file", "for the academic calendar event. prev_desc - Description for the", "delete_grade(request): # \"\"\" # It deletes the grade of the", "user_check(request): \"\"\" This function is used to check the type", "rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s =", "month >= 7 and month <= 12: return [1, 3,", "from file fathers_name - details of student from file mothers_name", "acadTtForm = \"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses", "# \"\"\" # It adds the basic profile information like", "= request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor')", "'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method", "######################################################### # ''' # # view to add attendance data", "# print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course)", "timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent'", "holding the convenor/coconvenor designation # student - the student object", "['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2':", "contains convenor # c - the designation object that contains", "chain from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect,", "grade - grade to be added in the student course", "hall # s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/')", "= to_date[0].split('-') to_date = [int(i) for i in to_date] to_date", "request - contains metadata about the requested page. # @variables:", "sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num =", "contains where the student will become # convenor or coconvenor", "new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme)", "to store that the particualr student is # holding the", "pass # print(request.POST) # choices = request.POST.getlist('choice') # for i", "sem = int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id,", "context= { 'tab_id' :['2','1'] } if request.method == 'POST' and", "of the student # user - the User object of", "database exam_t - all exam timetable from database \"\"\" if", "exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme", "# desig_id - to check the designation of the user.", "Get the object of the calendar instance from the database", "user_details - the rollno of the student required to check", "\"\"\" To add details of new upcoming students in the", "the academic timetable objects calendar - all the academic calender", "requested page # pk - the primary key of that", "# print(data) # return JsonResponse(data) # else: # data =", "from database exam_t - all exam timetable from database \"\"\"", "course - get the course details # \"\"\" # current_user", "Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\")", "minute object to the database. # @param: # request -", "request.FILES: # form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): #", "add_calendar(request): \"\"\" to add an entry to the academic calendar", "render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can upload", "database. # @param: # request - contains metadata about the", "# else: # return HttpResponse(\"Data Does Not Exist\") # return", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st = request.POST['delete']", "# e.delete() # u.delete() # return JsonResponse(data)# ######################################################### # '''", "# student - the list students that is a senator", "#print (temp) # print (current_user) # acadadmin = temp.working #", "add_advanced_profile(request): # \"\"\" # It adds the advance profile information", "now = datetime.datetime.now() year = int(now.year) if sem[0] == 2:", "= Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= { #", "batch course - gets the course curr_key - gets the", "the new senator # data - data of the student", "# db.name = name.upper() # db.id = roll # db.batch", "= get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username = e.user.username)", "= Course.objects.all() # for i in courses: # if i.course_id", "the student # @param: # request - contains metadata about", "to get faculty list from database @param: request - contains", "if result == \"Convenor\": # hDes.designation = s # else:", "# to remove a convenor/coconvenor from the position # @param:", "from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" # to add", "procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag,", "a senator from the position # @param: # request -", "stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for", "get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student =", ":['2','1'] } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel", "HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1']", "checking the designation of the current user # acadadmin -", "curriculum # # #################################### @login_required def curriculum(request): \"\"\" This function", "username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no,", "event. desc - Description for the academic calendar event. prev_desc", "'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list'", "- workbook of xlsx file title - formatting variable of", "t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request):", "stu not in registered_students: unregistered_students.add(stu) data = [] m =", "# return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### #", "optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\"", "- xlsx sheet to be rendered titletext - formatting variable", "{ 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method == \"POST\":", "from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404,", "'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t,", "request.POST['option'] == '2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme,", "the minute object received from id to be deleted #", "= room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/')", "@variables: # s - the designation object that contains convenor", "category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization", "object of senator # hDes - holdsDesignation object to store", "- details of student from file batch - details of", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t =", "from form curriculum - Get data about curriculum from database", "return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify", "me etc of a student # @param: # request -", "curriculum_courses, # } # return render(request, \"ais/ais.html\", context) # else:", "time now - get current time year - getcurrent year", "- The starting date for the academic calendar event. to_date", "the authentication of the user. @param: request - contains metadata", "required user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) #", "objects calendar - all the academic calender objects context -", "e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i", "new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch']", "s - the designation object that contains senator # student", "'tab_id' :['3','1'] } if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id'])", "temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user)", "mother_name = mothers_name, cpi = 0, category = category, hall_no", "entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum", "# s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request):", "name of the student # roll - the rollno of", "course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else:", "check the designation of the user. # user_details - to", "calender examTtForm - the form required to add exam timetable", "from form request_sem - Semester from form curriculum - Get", "sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1 for i", "s.father_name = \"\" # s.mother_name = \"\" # s.hall_no =", "edit entries in a curriculum. It checkes the authentication of", "# print(request.POST['delete']) # data = request.POST['delete'] # d = data.split(\"-\")", "# return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\")", "- details of student from file department - details of", "curriculum - curriculum details form database ins - Inster data", "return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme'] now", "the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request)", "for context m - counter for Sl. No (in formated", "'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save()", "no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details =", "# acadadmin - student's address # final_user - details of", "batch - batch from form.REQUEST branch - branch from form.REQUEST", "id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, )", "entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch", "k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output", "This function is used to edit curriculum in database It", "contains metadata about the requested page. @variables: from_date - The", "} # return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/')", "\"\" request_sem = \"\" #for checking if the user has", "\" \" + str(room) # student.save() # s = Student.objects.get(id=student)", "'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return", "It adds the advance profile information like hall no, room", "profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" # It adds", "created in database stud_data - new student object created in", "AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length =", "get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes =", "== \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch =", "the students context - the datas to be displayed in", "# print(request.POST) # choices = request.POST.getlist('choice') # for i in", "from file department - details of student from file specialization", "ins - data is stored in database \"\"\" if user_check(request):", "from_date = [int(i) for i in from_date] from_date = datetime.datetime(*from_date).date()", "'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses,", "{ # 'rollno': pk, # } # s.delete() # e.delete()", "- current month \"\"\" now = datetime.datetime.now() month = int(now.month)", "obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else:", "while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch']", "render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] } return", "CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot in course_slots:", "name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404(", "requested page @variables: dele - data being deleted from database", "def delete_advanced_profile(request): # \"\"\" # to delete the advance information", "batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= {", "the type of user. It checkes the authentication of the", "minimum credit for a current semester that a student must", "hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch =", "generate preresgistration report after pre-registration @param: request - contains metadata", "append it to an array. # sem - Get the", "update_calendar(request): \"\"\" to update an entry to the academic calendar", ": curriculum, # 'tab_id' :['3','1'] # } courses = Course.objects.all()", "- data of delete dictionary in post request t -", "request.method == \"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno'))", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method ==", "of the student # \"\"\" if request.method == \"POST\": name", "is used to edit curriculum in database It checkes the", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES:", "This function generates semester grade sheet @variables: now - current", "= request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno)", "print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) #", "db.id = roll # db.batch = batch # db.programme =", "courses, # 'course_type' : course_type, # 'curriculum' : curriculum, #", "\"\" acadTtForm = \"\" calendar = \"\" this_sem_courses = \"\"", "- the designation object that contains convenor # c -", "the next semester obj - All the registration details appended", "extraInfo objects of the student # user - the User", "def next_curriculum(request): \"\"\" This function is used to decide curriculum", "types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context =", "= Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request,", "in and must be acadadmin @param: request - contains metadata", "metadata about the requested page # @variables: # rollno -", "data in databsae. User must be logged in and must", "sem_cred = Get credit details from forms and the append", "course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from", "= request.POST['delete'] # d = data.split(\"-\") # id = d[0]", "final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True else: return", "desig_id - mother's name of the student acadadmin - student's", "type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list =", "objects department - all the departments in the college attendance", "\"\"\" acad-admin can delete the outdated timetable from the server.", "= {} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk):", "student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user", "pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for i in", "== \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem", "def update_calendar(request): \"\"\" to update an entry to the academic", "of user from database desig_id - check for designation acadadmin", "course_code - course_code from form.REQUEST course_name - course-name from form.REQUEST", "= request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id", "objects that holds the designation as a senator students -", "required to check if the student is available # mother", "from itertools import chain from django.contrib.auth.models import User from django.http", "context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get", "# It deletes the grade of the student # @param:", "else: course_list_2 = [1, 3, 5, 7] # examTtForm =", "page # @variables: # current_user - the username of the", "6, 8] @login_required def generatexlsheet(request): \"\"\" to generate Course List", "Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to", "request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch", "course_type from form.REQUEST ins - data is stored in database", "temporary variables for final output c - temporary variables for", "return True else: return False def get_context(request): \"\"\" This function", "as a senator students - all the objects in the", "Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign':", "acad-admin can delete the outdated exam timetable. @param: request -", "True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)]", "data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method", "'course_type': course_type, # 'curriculum_course': curriculum_courses, # } # return render(request,", "grade is added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/')", "User object of the student # s - the student", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": #", "student object created in database desig - get designation object", "{} # return JsonResponse(data) # else: # data = {}", "optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch =", "flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username", "s.hall_no = hall # s.room_no = room # s.save() #", "logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save()", "= request.POST.get('hall') # room = request.POST.get('room') # cpi = request.POST.get('cpi')", "- all the exam timetable objects timetable - all the", "= ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student',", "Minute################## # @csrf_exempt def addMinute(request): # \"\"\" # to add", "deleted # \"\"\" # if request.method == \"POST\": # data", "form request_branch - Branch from form request_programme - Programme from", "course_name - course-name from form.REQUEST course_id - course_id from database", "request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-')", "- temporary array to add data to variable data k", "senator extra - all the extraInfor objects exam_t - all", "= request.POST.get('mother') # add = request.POST.get('address') # hall = request.POST.get('hall')", ": procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' :", "# It adds the basic profile information like username,password, name,", "\"\"\" # to remove a senator from the position #", "HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == 'POST':", "request t - Object of time table to be deleted", "Inster data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if", "# sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in", "request timetable - all timetable from database exam_t - all", "# courses = Course.objects.all() # for i in courses: #", "# ###################################################### # # ##########Student basic profile################## # @csrf_exempt def", "context - the datas to be displayed in the webpage", "# current_user - gets the data of current user. #", "if the user has searched for any particular curriculum if", "to store that the particualr student is holding the senator", "- Batch from form request_branch - Branch from form request_programme", "course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits", "batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= {", "# if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s", "\"\"\" pass # if request.POST: # s = get_object_or_404(Designation, name=\"Senator\")", "# desig_id - checking the designation of the current user", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST':", "to save new event to the academic calendar. \"\"\" if", "\"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username", "id=einfo, programme = programme_name, batch=batch_year, batch_id = batch, father_name =", "new convenor/coconvenor # data - data of the student to", "= datetime.datetime.now() year = int(now.year) if sem[0] == 2: sem", "id of the minute object to be deleted # t", "'designation': hDes.designation.name, # } # return JsonResponse(data) # else: #", "\"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as", "title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20)", "in the student course - course ofwhich the grade is", "# @variables: # data - the id of the minute", "be displayed in the webpage # \"\"\" s = Designation.objects.get(name='Convenor')", "== 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem')", "Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp)", "enrolled in # ph - the phone number of the", "given pk # hDes - the holdDesignation object that stores", "\"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional,", "of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet()", "request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user = extraInfo.user #", "for the academic caldendar event. desc - Description for the", "object of the new convenor/coconvenor # data - data of", "= \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception", "batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response", "request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception as e:", "user. # user_details - gets the details of the required", "excel file sheet - sheet no in excel file roll_no", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem =", "= fathers_name, mother_name = mothers_name, cpi = 0, category =", "# s.save() # else: # return HttpResponse(\"Data Does Not Exist\")", "= ' + course.code + '.xlsx' response['Content-Disposition'] = st return", "not student: # data = {} # return JsonResponse(data) #", "- io Bytes object to write to xlsx file book", "students that is a senator # hDes - the holdDesignation", "stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id'", "- contains metadata about the requested page. @variables: examTtForm -", "designation as a convenor CoConvenor - the extraInfo objects that", "that contains where the student will become # convenor or", "as e: request_batch = \"\" request_branch = \"\" request_programme =", "context['tab_id'][0]='6' if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch", "working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no =", "= request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db = Student()", "currs - get curriculum details reg - create registeration object", "List of Registered Students @param: request - contains metadata about", "request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows):", "# return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): #", "data of the student to be displayed in teh webpage", "student course - course ofwhich the grade is added \"\"\"", "# extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes", "password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user,", "requested page @variables: acadTtForm - the form to add academic", "as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context", "exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if", "request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request,", "+ str(\" \") + batch.discipline.acronym + str(\" \") + str(batch.year))", "xhtml2pdf import pisa from itertools import chain from django.contrib.auth.models import", "sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value)", "grade to be added in the student course - course", "dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\"", "now - current datetime month - current month \"\"\" now", ": assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'],", "must take # @param: # request - contains metadata about", "== \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id =", "function gets basic gata from database to send to template", "the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar =", "database courses_type - get course types from database \"\"\" if", "= request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' : courses,", "Object of Exam time table to be deleted \"\"\" if", "# hDes.user = extraInfo.user # hDes.working = extraInfo.user # if", "profiles - gets the excel file having data excel -", "= True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval", "curriculum details reg - create registeration object in registeration table", "# if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name =", "event. desc - Description for the academic calendar event. c", "== \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return", "the academic calendar event. to_date - The ending date for", "def generatexlsheet(request): \"\"\" to generate Course List of Registered Students", "xlsx file title - formatting variable of title the workbook", "the requested page @variables: programme - programme from form.REQUEST now", "i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e =", "if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum =", "if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch =", "# data - data of the student to be hidden", "applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm,", "of the semester. @param: request - contains metadata about the", "user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id", "add_basic_profile(request): # \"\"\" # It adds the basic profile information", "acadadmin - deatils of the acad admin # father -", "data - data of the student to be hidden in", "request user_details - extract details of user from database desig_id", "about the requested page @variables: current_user - get user from", "be deleted # t - the minute object received from", "= 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c =", "- contains metadata about the requested page @variables: acadTtForm -", "student = Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username,", "All the registration details appended into one data - Formated", "= HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\"))", "'attachment; filename = ' + batch.name + batch.discipline.acronym + str(batch.year)", "k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') #", "Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") |", "the additional courses # @param: # request - contains metadata", "final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method ==", "sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if sem[0] ==", "objects that holds the designation as a dean student -", "type of) of the semester. @param: request - contains metadata", "k = str(user_details).split() # print(k) # final_user = k[2] #", "{ # 'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses,", "or des.designation == c: # designation = des.designation.name # des.delete()", "\"\"\" to add an entry to the academic calendar to", "from database credits - credits from form.REQUEST optional - optional", "course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course':", "request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except", "page @variables: senates - the extraInfo objects that holds the", "objects context - the datas to be displayed in the", "' + course.code + '.xlsx' response['Content-Disposition'] = st return response", "hall no, room no, # profile picture, about me etc", "uploaded @param: request - contains metadata about the requested page.", "data = {} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request,", "tha data of thsi semester courses next_sem_courses - the data", "(str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method ==", "+= 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for", "contains metadata about the requested page # @variables: # current_user", "return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] }", "assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status", "flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance", "+ str(room) # student.save() # s = Student.objects.get(id=student) # s.father_name=father", "in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context =", "the student to be displayed in teh webpage # \"\"\"", "details of student from file address - details of student", "request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception as e:", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme", "request_sem - Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "basic gata from database to send to template @param: request", "= s # hDes.save() # student = Student.objects.get(id=extraInfo) # data", "stud_data - new student object created in database desig -", "course_list_2 = [1, 3, 5, 7] # examTtForm = ExamTimetableForm()", "object created in database stud_data - new student object created", "\"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method", "'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else:", "print(curriculum_courses) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE #", "dictionary in post request timetable - all timetable from database", "# return HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\":", "'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length'", "= branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type =", "next sem and store data in databsae. User must be", "= programme_name, discipline__acronym = dept, year = batch_year).first() user =", "course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem,", "starting date for the academic calendar event. to_date - The", "to be updated. @param: request - contains metadata about the", "and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return", "get stdents data from database ans - Formatted Array to", "@login_required def user_check(request): \"\"\" This function is used to check", "file sheet - sheet no in excel file roll_no -", "student from file phone_no - details of student from file", "get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as", "the update it. # \"\"\" if request.method==\"POST\": sem_cred = []", "Description for the academic calendar event. prev_desc - Description for", "# final_user = k[2] # if (str(acadadmin) != str(final_user)): #", "object to the database. # @param: # request - contains", "request - contains metadata about the requested page @variables: acadTtForm", "and request.FILES: # form = MinuteForm(request.POST, request.FILES) # if form.is_valid():", "semester courses next_sem_courses - the data of next semester courses", "caldendar event. desc - Description for the academic calendar event.", "} if request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date", "= Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes =", "\"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses':", "new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch", "metadata about the requested page. # @variables: # choices -", "for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first()", "else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year)", "hDes.user = extraInfo.user # hDes.working = extraInfo.user # if result", "delete curriculum entry in database It checkes the authentication of", "import json import os import xlrd import logging from io", "== \"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice') #", "# if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete'])", "BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from", "= batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3']", "current semester from current time now - get current time", "{ 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm =", "# student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation,", "current user. # user_details - gets the details of the", "attendance data to database # def curriculum(request): # ''' def", "Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to", "request.POST.get('mother') # add = request.POST.get('address') # hall = request.POST.get('hall') #", "# @variables: # choices - selected addtional courses by the", "context) @login_required def edit_curriculum(request): \"\"\" This function is used to", "return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t", "= sem) # print(curriculum_courses) # courses = Course.objects.all() # course_type", "semester from form.REQUEST course_code - course_code from form.REQUEST course_name -", "= Course.objects.all() # course_type = Constants.COURSE_TYPE # context= { #", "homepage of the application. It checkes the authentication of the", "from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models", "= BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size':", "from form.REQUEST course_code - course_code from form.REQUEST course_name - course-name", "about the requested page # @variables: # current_user - details", "form request_programme - Programme from form request_sem - Semester from", "of the student # user_details - the rollno of the", "HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\"", "e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date,", "the requested page. # @variables: # choices - selected addtional", "outdated timetable from the server. @param: request - contains metadata", "as e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date,", "page. @param: request - contains metadata about the requested page", "\"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated =", "@login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\"", "m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z)", "request.POST['delete'] # arr = st.split(\"-\") # stu = arr[0] #", "new_reg=[] for c in courses: reg=course_registration( course_id = c, semester_id=sem_id,", "user created in database einfo - new extrainfo object created", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\"", "the rollno of the student # batch - the current", "optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum =", "'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data'", "credits from form.REQUEST optional - optional from form.REQUEST course_type -", "- counter for Sl. No (in formated data) z -", "the basic profile information like username,password, name, # rollno, etc", "the student # data - tag whether to delete it", "#Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year =", "Batch @login_required def user_check(request): \"\"\" This function is used to", "is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={", "an existing senate meeting minute object from the database. #", "= CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot in", "course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\"", "branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\":", "return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## # @csrf_exempt", "if the student is available # desig_id - mother 's", "database table # @variables: # e - the extraInfo objects", "for the minimum credits from the database and the update", "# s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\")", "+ '.xlsx' response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request):", "the requested page @variables: programme - programme from form.REQUEST batch", "- contains metadata about the requested page @variables: sem -", "data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp", "\"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\"", "- Get the object for the minimum credits from the", "courses = Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable", "context={ # 'courses' : courses, # 'course_type' : course_type, #", "'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses,", "\"\"\" This function is used to decide curriculum for new", "str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response =", "data = { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, #", "no of where the student stays # room no -", "page. @variables: request_batch - Batch from form request_branch - Branch", "# return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: #", "of xlsx file title - formatting variable of title the", "sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet @variables: now", "programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept,", "sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name +", "Convenor # result - the data that contains where the", "object of Co Convenor # result - the data that", "holdsDesignation object to store that the particualr student is holding", "month = int(now.month) if month >= 7 and month <=", "\"\"\" # if request.method == \"POST\": # data = request.POST['delete']", "to remove a convenor/coconvenor from the position # @param: #", "= get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) #", "address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo,", "from the databases to display it on the page. @param:", "add exam timetable exam_t - all the exam timetable objects", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method", "from form.REQUEST course_name - course-name from form.REQUEST course_id - course_id", "p # hDes.save() # data = { # 'name': extraInfo.user.username,", "- the name of the student # roll - the", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request):", "the objects in the Student class Convenor - the extraInfo", "= Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t =", "to be deleted # data - data of the student", "pisa from itertools import chain from django.contrib.auth.models import User from", "post request t - Object of time table to be", "category = category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem,", "metadata about the requested page # @variables: # name -", "for Acadadmin final_user - final designation of request user \"\"\"", "b - temporary variables for final output c - temporary", "\"POST\": # print(\"confirm hone wala hai\") # print(request.POST) return HttpResponseRedirect('/aims/')", "curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return render(request,", "= programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name", "curriculum - Get data about curriculum from database courses -", "Deletes the student from the database # @param: # request", "database einfo - new extrainfo object created in database stud_data", "excel file roll_no - details of student from file first_name", "c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request):", "the minute object to be deleted # t - the", "current datetime month - current month \"\"\" now = datetime.datetime.now()", "it on the page. @param: request - contains metadata about", "Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch,", "to check if the student is available # desig_id -", "logged in user # user_details - the details of the", "# rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address)", "request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception as", "semester obj - All the registration details appended into one", "\"\" #for checking if the user has searched for any", "request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as e:", "context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates", "# user_details - to get the details of the required", "HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st", "holds the designation as a senator students - all the", "available desig_id - mother's name of the student acadadmin -", "to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "from file phone_no - details of student from file address", "to delete curriculum entry in database It checkes the authentication", "stays # room no - hostel room no # \"\"\"", "last_name - details of student from file email - details", "programme).filter(sem = sem) # print(curriculum_courses) # courses = Course.objects.all() #", "contains metadata about the requested page. # @variables: # sem_cred", "rollno of the student required to check if the student", "\"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') #", "obj = course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\"", "rollno, etc of a student # @param: # request -", "username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp", "titletext - formatting variable of title text dep - temporary", "batch from form sem - stores the next semester obj", "return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function", "title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value)", "= get_object_or_404(Student, id=e) # data = { # 'rollno': pk,", "details of the current user # desig_id - checking the", "# data - tag whether to delete it or not", "'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method == \"POST\": try:", "return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function", "# # ###################################################### # # ##########Student basic profile################## # @csrf_exempt", "# @csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to remove", "the User object of the student # s - the", "JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import get_template", "'rollno': roll.id, # 'programme': programme, # 'phoneno': ph, # 'batch':", "the designation as a convenor CoConvenor - the extraInfo objects", "programme from form.REQUEST batch - batch from form.REQUEST branch -", "id to be deleted # \"\"\" # if request.method ==", "to an array. # sem - Get the object for", "curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm'", "from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and", "about the requested page @variables: dele - data being deleted", ": pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' :", "from the position # @param: # request - contains metadata", "if sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem =", "hall_no - details of student from file programme - details", "ph - the phone number of the student # \"\"\"", "- the form to add a senate meeting minutes acadTtForm", "procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'],", "description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required def", "student's cpi # hall - hall no of where the", "= \"\" course_type = \"\" timetable = \"\" exam_t =", "d[0] # course = d[2] # sem = int(d[3]) #", "[] for i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name)", "credits from the database and the update it. # \"\"\"", "db = Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name =", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\":", "a student # @param: # request - contains metadata about", "def delete_curriculum(request): \"\"\" This function is used to delete curriculum", "False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval =", "Programme from form request_sem - Semester from form curriculum -", "\"\"\" to get faculty list from database @param: request -", "the object of the calendar instance from the database for", "to be displayed in the webpage \"\"\" if user_check(request): return", "designation # student - the student object of the new", "the requested page. @variables: data - data of delete dictionary", "Course.objects.all() # for i in courses: # if i.course_id not", "the academic calendar to be uploaded @param: request - contains", "- All the registration details appended into one data -", "calender objects department - all the departments in the college", "= str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close()", "room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details", "i=1 while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in", "- the primary key of the student's record in the", "for designation acadadmin - designation for Acadadmin final_user - final", "break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme=", "to be added in the student course - course ofwhich", "mother's name of the student acadadmin - student's address subject", "a senator extra - all the extraInfor objects exam_t -", "Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) #", "check if the student is available # desig_id - mother", "first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title,", "if (str(acadadmin) != str(final_user)): return True else: return False def", "- extraInfo object of the student with that rollno #", "add exam timetable Dean - the extraInfo objects that holds", "in students: if stu not in registered_students: unregistered_students.add(stu) data =", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all()", "from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id'", "in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description =", "else: # return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted", "+ batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return", "hall - hall no of where the student stays #", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request):", "user # user_details - the details of the current user", "sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if", "# roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch", "# extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p", "form sem - stores the next semester obj - All", "- Description for the academic calendar event. c = object", "be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method ==", "get current time year - getcurrent year batch - gets", "- get current time year - getcurrent year batch -", "else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors##################", ":['3','1'] } return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context)", "datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c", "if request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\" in", "has searched for any particular curriculum if request_batch == \"\"", "workbook normaltext - formatting variable for normal text sheet -", "get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user = student.user)", "print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable to delete", "is to be updated. get_calendar_details = Get the object of", "to add a new student convenor/coconvenor # @param: # request", "- new student object created in database desig - get", "about the requested page # @variables: # current_user - gets", "= [1, 3, 5, 7] # examTtForm = ExamTimetableForm() #", "database.User must be logged in and must be acadadmin @param:", "created in database einfo - new extrainfo object created in", "programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\"", "variable for normal text sheet - xlsx sheet to be", "of Convenor # p - designation object of Co Convenor", "def delete_grade(request): # \"\"\" # It deletes the grade of", "the holdDesignation object that stores the # information that the", "= Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list =", "timetable from database exam_t - all exam timetable from database", "to update the additional courses # @param: # request -", "== 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid():", "# # ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): #", "holds the designation as a dean student - the students", "# ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" # to", "and month <= 12: return [1, 3, 5, 7] else:", "of title the workbook subtitle - formatting variable of subtitle", "'courses' : courses, # 'course_type' : course_type, # 'curriculum' :", "get user from request user_details - extract details of user", "# t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # #", "else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym", "of the student @param: request - contains metadata about the", "request - contains metadata about the requested page. @variables: profiles", "now - current date from system year - current year", "requested page @variables: sem - get current semester from current", "information of the student # @param: # request - contains", "form.REQUEST course_code - course_code from form.REQUEST course_name - course-name from", "- temporary variables for final output st - temporary variables", "= HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user", "{ 'tab_id' :['5','1'] } if request.method == \"POST\": i=1 while", "= [2, 4, 6, 8] else: course_list_2 = [1, 3,", "hDes - holdsDesignation object to store that the particualr student", "return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes", "of the student's record in the database table # @variables:", "request.POST.get('father') # mother = request.POST.get('mother') # add = request.POST.get('address') #", "the requested page. @variables: examTtForm - data of delete dictionary", "calendar instance from the database for the previous Description. \"\"\"", "the senator designation # student - the student object of", "render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def", "grades, # 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context)", "of the student # add - student's address # cpi", "c - the designation object that contains co convenor #", "'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' :", "request.POST['sem'] except Exception as e: request_batch = \"\" request_branch =", "procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'],", "details of student from file programme - details of student", "from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e: from_date=\"\"", "render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json')", "No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k", "a senate meeting minutes acadTtForm - the form to add", "= k[2] # if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/')", "add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable of the", "chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\",", "f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate", "contains metadata about the requested page @variables: programme - programme", "timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t,", "= [] # for des in hDes: # if des.designation", "id=pk) # user = get_object_or_404(User, username = e.user.username) # s", "dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13", "@variables: # sem_cred = Get credit details from forms and", "temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k =", "page. @variables: profiles - gets the excel file having data", "# rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo", "= request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user = extraInfo.user", "specialization - details of student from file hall_no - details", "book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title)", "sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50)", ": procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' :", "user - the User object of the student # s", "# hDes.working = extraInfo.user # hDes.designation = s # hDes.save()", "semester that a student must take # @param: # request", "import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits,", "the attendance objects of the students context - the datas", "that stores the # information that the particular student is", "datas to be displayed in the webpage \"\"\" if user_check(request):", "data of delete dictionary in post request t - Object", "context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\",", "in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True", "name - the name of the student # roll -", "course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context)", "- the phone number of the student # \"\"\" if", "phone number of the student # \"\"\" if request.method ==", "- the data of next semester courses courses - all", "= s # else: # hDes.designation = p # hDes.save()", "'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+", "generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration @param: request", "e.delete() # u.delete() # return JsonResponse(data)# ######################################################### # ''' #", "curriculum from database courses - get courses from database courses_type", "add_optional(request): # \"\"\" # acadmic admin to update the additional", "sheet to be rendered titletext - formatting variable of title", "of student from file programme - details of student from", "checkes the authentication of the user. @param: request - contains", "sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle)", "the requested page. @variables: request_batch - Batch from form request_branch", "JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt def", "current user # desig_id - checking the designation of the", "if (str(p.course_id) == course): # print(p.course_id) # p.delete() # else:", "- details of student from file mothers_name - details of", "return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id'", "'hod_flag' : hod_flag, 'account_flag' : account_flag } return context @login_required", "c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst", "deleted # data - data of the student to be", "- gets the curriculum from database obj - get stdents", "True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval =", "calendar event. c = object to save new event to", "examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses", "= 'application/vnd.ms-excel') st = 'attachment; filename = ' + batch.name", "of data faculty_list - list of faculty \"\"\" try: f1", "# @variables: # current_user - the username of the logged", "databases to display it on the page. @param: request -", ":['3','3'] } return render(request, \"ais/ais.html\", context) else: context= { 'tab_id'", "- getcurrent year batch - gets the batch from form", "of Co Convenor # result - the data that contains", "book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet =", "= int(now.month) if month >= 7 and month <= 12:", "of student from file department - details of student from", "designation object of senator # hDes - holdsDesignation object to", "the extraInfo objects of the student # user - the", "delete an existing senate meeting minute object from the database.", "else: break i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------", "registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu in students:", "'tab_id' :['5','1'] } if request.method == 'POST': try: request_batch =", "# return HttpResponse('sucess') # else: # return HttpResponse('not uploaded') #", "from database courses_type - get course types from database \"\"\"", "= datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date =", "= get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes", "page. @variables: from_date - The starting date for the academic", "batch.name + str(\" \") + batch.discipline.acronym + str(\" \") +", "Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html})", "details of student from file title - details of student", "- the list students that is a senator # hDes", "used to check the designation ID. # extraInfo - extraInfo", "str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0)", "curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses =", "batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[] for i", "t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ######################################################", "update it. # \"\"\" if request.method==\"POST\": sem_cred = [] #", "object from the database. # @param: # request - contains", "True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark =", "= str(hall) + \" \" + str(room) # student.save() #", "= Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first()", "procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date'", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method", "\"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 =", "remove a senator from the position # @param: # request", "return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It", "sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif", "sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True", "len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat:", "normal text sheet - xlsx sheet to be rendered titletext", "curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False,", "student: # data = {} # return JsonResponse(data) # else:", "about the requested page @variables: request_batch - Batch from form", "# u.delete() # return JsonResponse(data)# ######################################################### # ''' # #", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6'", "text sheet - xlsx sheet to be rendered titletext -", "ans = [] for i in registered_courses: k = []", "object to save new event to the academic calendar. \"\"\"", "function is used to decide curriculum for new batch. It", "7 and month <= 12: return [1, 3, 5, 7]", "= get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user =", "prev_desc - Description for the previous event which is to", "form.REQUEST course_type - course_type from form.REQUEST ins - data is", "= Grades.objects.filter(student_id=id, sem=sem) # for p in s: # if", "page. @variables: f1,f2,f3 - temporary varibles faculty - details of", "courses_type - get course types from database \"\"\" if user_check(request):", "sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1 for", "course_type, # 'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\",", "(str(acadadmin) != str(final_user)): return True else: return False def get_context(request):", "- course_code from form.REQUEST course_name - course-name from form.REQUEST course_id", "- designation object of Convenor # p - designation object", "get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date", "exam timtable of the ongoing semester. @param: request - contains", "s = Grades.objects.filter(student_id=id, sem=sem) # for p in s: #", "stu in students: if stu not in registered_students: unregistered_students.add(stu) data", "- contains metadata about the requested page @variables: request_batch -", "request_sem) # context={ # 'courses' : courses, # 'course_type' :", "time table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "- hostel room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username)", "student is available # mother - mother's name of the", "@param: # request - contains metadata about the requested page.", "context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch", "is holding the senator designation # student - the student", "request - contains metadata about the requested page. @variables: data", "temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print", "sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num", "Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme", "{ 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id'", "Course List of Registered Students @param: request - contains metadata", "- details of student from file first_name - details of", "all the objects in the Student class Convenor - the", "to see curriculum and edit entries in a curriculum. It", "Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark", "the requested page # @variables: # current_user - father's name", "delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam timetable. @param:", "requested page @variables: batch - gets the batch course -", "# def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" #", "of the required user. # \"\"\" # current_user = get_object_or_404(User,", "= { # 'name': name, # 'rollno': roll.id, # 'programme':", "from file first_name - details of student from file last_name", "@variables: current_user - get user from request user_details - extract", "the requested page. @variables: from_date - The starting date for", "= request.POST['sem'] except Exception as e: request_batch = \"\" request_branch", ":['4','1'] } if request.method == \"POST\": try: from_date = request.POST.getlist('from_date')", "= book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle", "and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return", "holds the designation as a convenor CoConvenor - the extraInfo", "objects calendar - all the academic calender objects department -", "'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else: return render(request,", "# timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context =", "username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division", "= sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if sem[0]", "= HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user) #", "of the student user_details - the rollno of the student", "= desig_id).first() #print (temp) # print (current_user) # acadadmin =", "check if the student is available # mother - mother's", "and also fetches the available data from the databases to", "programme - details of student from file batch - details", "# current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() #", "# course_type = Constants.COURSE_TYPE # context= { # 'courses': courses,", "\"\"\" # Deletes the student from the database # @param:", "the requested page # @variables: # current_user - the username", "year batch - batch form form curriculum - curriculum details", "render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to delete", "return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt", "the student # rollno - the rollno of the student", "1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO()", "Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() #", "extraInfo objects that holds the designation as a convenor CoConvenor", "= Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin", "Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if request.method ==", "@variables: request_batch - Batch from form request_branch - Branch from", "# \"\"\" # It deletes the grade of the student", "# student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user =", "InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for stu", "metadata about the requested page # @variables: # s -", "= [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output =", "\"\" and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else:", "== 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid():", "== \"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) #", "from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1']", "to add exam timetable Dean - the extraInfo objects that", "extraInfo.user # hDes.working = extraInfo.user # hDes.designation = s #", "# curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context=", "in database stud_data - new student object created in database", "father_name = fathers_name, mother_name = mothers_name, cpi = 0, category", "the requested page # @variables: # rollno - rollno of", "name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes =", "student # programme - the programme the student is enrolled", "student currs - get curriculum details reg - create registeration", "the student required to check if the student is available", "data) z - temporary array to add data to variable", "# return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\"", "render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload", "student # \"\"\" if request.method == \"POST\": name = request.POST.get('name')", "= batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[] for", "sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel')", "basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" # It", "curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else: return", "request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"])", "return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required", "of the minute object to be deleted # t -", "registered_courses.append(i) ans = [] for i in registered_courses: k =", "= e.user.username) # s = get_object_or_404(Student, id=e) # data =", "acad-admin can upload the time table(any type of) of the", "details appended into one data - Formated data for context", "\"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id", "d = data.split(\"-\") # id = d[0] # course =", "== \"\" and request_branch == \"\" and request_programme==\"\": curriculum =", "timetable exam_t - all the exam timetable objects timetable -", "curriculum entry in database It checkes the authentication of the", "user has searched for any particular curriculum if request_batch ==", "from database desig_id - check for designation acadadmin - designation", "request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0]", "- get user from request user_details - extract details of", "# for i in courses: # if i.course_id not in", "holdDesignation object that stores the # information that the particular", "request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] #", "output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True,", "the particualr student is holding the senator designation # student", "Convenor') # if request.method == 'POST': # rollno = request.POST.get('rollno_convenor')", "ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch = request.POST.get('batch') #", "in databsae. User must be logged in and must be", "variables z - temporary variables for final output b -", "5, 7] # examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm()", "request.POST.getlist('choice') # for i in choices: # course = Course.objects.all().filter(course_id=i).first()", "no, room no, # profile picture, about me etc of", "ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id = roll #", "for i in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request):", "student object with the given pk # hDes - the", "else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): #", "all the academic calender objects context - the datas to", "- the id of the minute object to be deleted", "account_flag = obj.account_status except Exception as e: examTtForm = \"\"", "object for the minimum credits from the database and the", "convenor/coconvenor # extraInfo - extraInfo object of the student with", "hDes.designation = s # else: # hDes.designation = p #", "Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context) # #", "for i in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name)", "= ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id = roll", "@login_required def delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable", "\"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\",", "= User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo =", "account_flag } return context @login_required def homepage(request): \"\"\" This function", "is used to delete curriculum entry in database It checkes", "add a new student convenor/coconvenor # @param: # request -", "calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses =", "(current_user) # acadadmin = temp.working # k = str(user_details).split() #", "[] # sem_cred.append(0) # for i in range(1, 10): #", "the acad admin # father - father's name of the", "desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date", "curriculum in database It checkes the authentication of the user", "hDes: # if des.designation == s or des.designation == c:", "- the data that contains where the student will become", "batch_id = batch, father_name = fathers_name, mother_name = mothers_name, cpi", "s - the student object from the requested rollno #", "programme - programme from form.REQUEST batch - batch from form.REQUEST", "- extract details of user from database desig_id - check", "'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign':", "the academic person. # course - Course details which is", "Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course'] #", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if", "course_type = \"\" timetable = \"\" exam_t = \"\" pass", "Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import", "= str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response =", "# to add a new senate meeting minute object to", "# final_user - details of the user # sem -", "# # return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') #", "designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem)", "any particular curriculum if request_batch == \"\" and request_branch ==", "can delete the outdated timetable from the server. @param: request", "f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name =", "the course curr_key - gets the curriculum from database obj", "meetings - the all meeting objects held in senator meetings", "s - the designation object that contains convenor # c", "the convenor/coconvenor # extraInfo - extraInfo object of the student", "in courses: # if i.course_id not in choices: # i.acad_selection", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course']", "if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode))", "senates - the extraInfo objects that holds the designation as", "context) @login_required def next_curriculum(request): \"\"\" This function is used to", "ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold':", "file title - details of student from file dob -", "\"\"\" This function is used to delete curriculum entry in", "holds the designation as a coconvenor meetings - the all", "{ 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context= {", "- the all meeting objects held in senator meetings minuteForm", "in registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k)", "= Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] == '1':", "f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for i", "'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # }", "@variables: profiles - gets the excel file having data excel", "it. # \"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0)", "credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except", "des.designation.name # des.delete() # data = { # 'id': pk,", "= { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme':", "to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context) @login_required", "from io import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf", "= ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context)", "response @login_required def add_new_profile (request): \"\"\" To add details of", "request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i)", "# 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, #", "requested page. @variables: data - data of delete dictionary in", "= request.POST['programme'] request_sem = request.POST['sem'] except Exception as e: request_batch", "new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context) #", "Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print", "# \"\"\" # Deletes the student from the database #", "acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "by the academic admin. # \"\"\" if request.method == \"POST\":", "+ '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def add_new_profile", "# @csrf_exempt def addMinute(request): # \"\"\" # to add a", "extraInfo - extraInfo object of the student with that rollno", "print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) #", "# hDes.user = extraInfo.user # hDes.working = extraInfo.user # hDes.designation", "year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name,", "course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\"", "id = d[0] # course = d[2] # sem =", "# student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student:", "= [] m = 1 for i in unregistered_students: z", "None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name =", "except Exception as e: request_batch = \"\" request_branch = \"\"", "= request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type", "- batch from form.REQUEST branch - branch from form.REQUEST sem", "= request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required", "filename = ' + batch.name + batch.discipline.acronym + str(batch.year) +", "True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User,", "file dob - details of student from file fathers_name -", "entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch =", "assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status", "return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\"", "this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list'", "details of student from file last_name - details of student", "object of the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk)", "of which the grade has to be added sem -", "# \"\"\" # to remove a senator from the position", "database credits - credits from form.REQUEST optional - optional from", "request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id", "Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot,", "student - the student object of the new senator #", "= HoldsDesignation.objects.filter(user = student.user) # designation = [] # for", "about the requested page. @variables: acadTtForm - data of delete", "des.designation == s or des.designation == c: # designation =", "z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z)", "= int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme", "exam_t - all exam timetable from database \"\"\" if user_check(request):", "- Course details which is selected by the academic admin.", "ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation", "senator designation # student - the student object of the", "if request.method == \"POST\": # st = request.POST['delete'] # arr", "academic person. # course - Course details which is selected", "@variables: programme - programme from form.REQUEST batch - batch from", "username,password, name, # rollno, etc of a student # @param:", "Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type", "about curriculum from database courses - get courses from database", "be displayed in the webpage this_sem_course - tha data of", "request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for i in", "if des.designation == s or des.designation == c: # designation", "#################################### # # curriculum # # #################################### @login_required def curriculum(request):", "get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request,", "contains metadata about the requested page @variables: current_user - father's", "context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This", "= True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst =", "flot.floated = True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst", "=True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat =", "roll # db.batch = batch # db.programme = programme #", "page @variables: programme - programme from form.REQUEST now - current", "return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\"", "name.upper() # db.id = roll # db.batch = batch #", "1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i", "user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first()", "student from file mothers_name - details of student from file", "Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar(", "for i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans", "form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() #", "rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo =", "= sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = []", "data = { # 'rollno': pk, # } # s.delete()", "timetable objects timetable - all the academic timetable objects calendar", "= from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e:", "\"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update an entry", "instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, )", "ID. # extraInfo - extraInfo object of the student with", "s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): #", "the requested page @variables: acadTtForm - the form to add", "of title text dep - temporary variables z - temporary", "arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name", "Object of time table to be deleted \"\"\" if user_check(request):", "if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request,", "about the requested page @variables: batch - gets the batch", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\"", "'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list'", "= to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\"", "deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\":", ".models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance,", "= int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)):", "contains metadata about the requested page @variables: senates - the", "def edit_curriculum(request): \"\"\" This function is used to edit curriculum", "i in registered_students: z = [] z.append(m) m += 1", "#Curriculum.objects.all() else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch =", ":['3','1'] # } courses = Course.objects.all() course_type = Constants.COURSE_TYPE html", "information that the particular student is a convenor/coconvenor to be", "AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True)", "designation acadadmin - designation for Acadadmin final_user - final designation", "- get current semester from current time now - get", "page. @variables: examTtForm - data of delete dictionary in post", "- the datas to be displayed in the webpage \"\"\"", "} # return render(request, \"ais/ais.html\", context) # else: # return", "name of the student # rollno - the rollno of", "sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem", "'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, # }", "acadadmin = temp.working k = str(user_details).split() final_user = k[2] except", "desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first()", "# 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context) #", "all exam timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "the designation as a dean student - the students as", "request_programme = request.POST['programme'] except Exception as e: request_batch = \"\"", "course_code from form.REQUEST course_name - course-name from form.REQUEST course_id -", "# @variables: # name - the name of the student", "Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k", "courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course':", "the webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c", "des in hDes: # if des.designation == s or des.designation", "'application/vnd.ms-excel') st = 'attachment; filename = ' + batch.name +", "# else: # return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\",", "\"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first()", "course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] ==", "acad-admin can upload the exam timtable of the ongoing semester.", "s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0]) #", "exam timetable exam_t - all the exam timetable objects timetable", "request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' : courses, #", "name, # rollno, etc of a student # @param: #", "upload the time table(any type of) of the semester. @param:", "request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\"", "= Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, # 'tab_id'", "courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] }", "from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def", "Co Convenor # result - the data that contains where", "{ 'tab_id' :['5','1'] } if request.method == 'POST': try: request_batch", "request.POST.get('hall') # room = request.POST.get('room') # cpi = request.POST.get('cpi') #", "i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name =", "that contains co convenor # student - the student object", "choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True #", "= programme) if request.POST['option'] == '1': new_curriculum=[] for i in", "str(final_user)): return True else: return False def get_context(request): \"\"\" This", "the datas to be displayed in the webpage this_sem_course -", "HoldsDesignation.objects.filter(user = student.user) # designation = [] # for des", "data = { # 'id': pk, # 'designation': designation, #", ":calendar, 'tab_id' :['4','1'] } if request.method == \"POST\": try: from_date", "available # mother - mother's name of the student #", "current user. # desig_id - to check the designation of", "if request.method == \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data)", "# ph - the phone number of the student #", "the required user. # desig_id - used to check the", "# return JsonResponse(data)# ######################################################### # ''' # # view to", "else: return False def get_context(request): \"\"\" This function gets basic", "# calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses", "of senator # hDes - holdsDesignation object to store that", "extract details of user from database desig_id - check for", "= Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center',", "# id = d[0] # course = d[2] # sem", "in s: # if (str(p.course_id) == course): # print(p.course_id) #", "7] # examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() #", "if request.method == \"POST\": # print(\"confirm hone wala hai\") #", "curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum", "Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)):", "- the username of the logged in user # user_details", "applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import", "# data = { # 'name': name, # 'rollno': roll.id,", "request_batch == \"\" and request_branch == \"\" and request_programme==\"\": curriculum", "gata from database to send to template @param: request -", "requested page @variables: request_batch - Batch from form request_branch -", "Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3))", "user # acadadmin - deatils of the acad admin #", "sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if request.method ==", "obj=\"\" registered_courses = [] for i in obj: if i.student_id.batch_id.year", "# st = request.POST['delete'] # arr = st.split(\"-\") # stu", "request.POST['programme'] request_sem = request.POST['sem'] except Exception as e: request_batch =", "exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm()", "context) # #################################### # # curriculum # # #################################### @login_required", "= request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception as", "HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\" # to", "batch. It checkes the authentication of the user and also", "request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem", "output - io Bytes object to write to xlsx file", "= \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 =", "request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def", "\"\"\" # It adds the advance profile information like hall", "assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True)", "ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type,", "except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass c =", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST) #", "login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from", "return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\" #", "django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from", "the requested page. @variables: f1,f2,f3 - temporary varibles faculty -", "about the requested page # @variables: # current_user - father's", "def homepage(request): \"\"\" This function is used to set up", "@variables: # rollno - rollno of the student to become", "as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = []", "current semester of the student # data - tag whether", "= batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context=", "text dep - temporary variables z - temporary variables for", "# db.save() # st.save() # data = { # 'name':", "in the database.User must be logged in and must be", "- the datas to be displayed in the webpage this_sem_course", "pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length,", "return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == 'POST':", "= Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result =", "to become the convenor/coconvenor # extraInfo - extraInfo object of", "roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.'", "[1, 3, 5, 7] # examTtForm = ExamTimetableForm() # acadTtForm", "return response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report", "for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method", ") desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig,", "function is used to delete curriculum entry in database It", "in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date =", "- details of student from file specialization - details of", "context) context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context)", "- temporary variables z - temporary variables for final output", "# cpi - student's cpi # hall - hall no", "the student # user_details - the rollno of the student", "appended into one data - Formated data for context m", "# for i in range(1, 10): # sem = \"sem_\"+\"1\"", "# sem_cred.append(0) # for i in range(1, 10): # sem", "hall_no, specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des", "import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required", "import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa", "the student to become the convenor/coconvenor # extraInfo - extraInfo", "= Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all()", "title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20)", "updated. @param: request - contains metadata about the requested page.", "# @variables: # s - the designation object that contains", "the student # user - the User object of the", "teh webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) #", "timetable - all timetable from database exam_t - all exam", "# rollno - the rollno of the student required to", "course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum =", "key of the student's record in the database table #", "acadTtForm - the form to add academic calender examTtForm -", "contains metadata about the requested page # @variables: # rollno", "semester of the student grade - grade to be added", "= str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext)", "data of thsi semester courses next_sem_courses - the data of", "True else: return False def get_context(request): \"\"\" This function gets", "- new extrainfo object created in database stud_data - new", "exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if", "the convenor/coconvenor designation # student - the student object of", "file user - new user created in database einfo -", "all the exam timetable objects timetable - all the academic", "formated data) z - temporary array to add data to", "requested page # @variables: # rollno - rollno of the", "HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme'] now =", "# @variables: # sem_cred = Get credit details from forms", "user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp =", "# #################################### # # curriculum # # #################################### @login_required def", "set up the homepage of the application. It checkes the", "contains metadata about the requested page @variables: request_batch - Batch", "'batch': batch # } # print(data) # return JsonResponse(data) #", "course.acad_selection = True # course.save() # courses = Course.objects.all() #", "# @variables: # current_user - father's name of the student", "'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'],", "import datetime import json import os import xlrd import logging", "- Description for the previous event which is to be", "def deleteMinute(request): # \"\"\" # to delete an existing senate", "= request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required", "page # pk - the primary key of the student's", "= request.POST.get('cpi') # student.address = str(hall) + \" \" +", "batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem)", "sem - stores the next semester obj - All the", "to the academic calendar to be updated. @param: request -", "- rollno of the student to become the convenor/coconvenor #", "= request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date =", "be deleted # data - data of the student to", "z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split()", "students context - the datas to be displayed in the", "minutes acadTtForm - the form to add academic calender examTtForm", "event. c = object to save new event to the", ">= 7 and month <= 12: return [1, 3, 5,", "To add details of new upcoming students in the database.User", "to be updated. get_calendar_details = Get the object of the", "pk, # 'designation': designation, # } # return JsonResponse(data)# ######################################################", "like hall no, room no, # profile picture, about me", "to add data to variable data k -temporary array to", "year - getcurrent year batch - gets the batch from", "details of student from file hall_no - details of student", "of the user. @param: request - contains metadata about the", "Sl. No (in formated data) z - temporary array to", "\"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function is used", "JsonResponse(data) # else: # father = request.POST.get('father') # mother =", "+ batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] =", "edit curriculum in database It checkes the authentication of the", "course - gets the course curr_key - gets the curriculum", "not Student.objects.filter(id=roll).exists(): # db = Student() # st = ExtraInfo.objects.get(id=roll.id)", "request.method == 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo =", "'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\",", "- the form required to add exam timetable Dean -", "batch=batch_year, batch_id = batch, father_name = fathers_name, mother_name = mothers_name,", "send to template @param: request - contains metadata about the", "# 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } # return", "of student from file specialization - details of student from", "z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title", "form curriculum - curriculum details form database ins - Inster", "in range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) #", "return JsonResponse(data)# ######################################################### # ''' # # view to add", "the requested page @variables: senates - the extraInfo objects that", "file fathers_name - details of student from file mothers_name -", "of current user. # user_details - gets the details of", "request.method == \"POST\": # data = request.POST['delete'] # t =", "= HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\"))", "= Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user = extraInfo.user", "return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to", "course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request,", "Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models", "i in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection =", "# s - designation object of senator # hDes -", "request.FILES) # if form.is_valid(): # form.save() # return HttpResponse('sucess') #", "for final output c - temporary variables for final output", "student from file dob - details of student from file", ":['3','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "{} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): #", "meeting minute object to the database. # @param: # request", "sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = [] for", "in to_date] to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\"", "the requested page. @variables: profiles - gets the excel file", "'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html',", "curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional,", ":['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\"", "[2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to generate", "# \"\"\" # to delete an existing senate meeting minute", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def", "of the student # acadadmin - student's address # final_user", "= \"\" acadTtForm = \"\" calendar = \"\" this_sem_courses =", "deleteConvenor(request, pk): # \"\"\" # to remove a convenor/coconvenor from", "sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme", "\"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co", "# \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User,", "= Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students =", "faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[]", "} return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "file email - details of student from file sex -", "ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else:", "= 'application/vnd.ms-excel') st = 'attachment; filename = ' + course.code", "optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id", "course_type = Constants.COURSE_TYPE # context= { # 'courses': courses, #", "course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for c in", "HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete'] t =", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list():", "\"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)]", "be acadadmin @param: request - contains metadata about the requested", "of the user # sem - current semester of the", "request.method == 'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES)", "last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.'", "- father's name of the student user_details - the rollno", "id=e) # data = { # 'rollno': pk, # }", "extraInfo.user # hDes.designation = s # hDes.save() # student =", "procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag", "HoldsDesignation, user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') #", "int(d[3]) # if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): #", "'.xlsx' response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request): \"\"\"", "== None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name", "st.save() # data = { # 'name': name, # 'rollno':", "HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models", "- details of student from file title - details of", "- data being deleted from database \"\"\" if user_check(request): return", "\"+ batch.name + str(\" \") + batch.discipline.acronym + str(\" \")", "user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2,", "= arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) #", "of the student acadadmin - student's address subject - subject", "student from file email - details of student from file", "object received from id to be deleted # \"\"\" #", "# user - the User object of the student #", "temporary varibles faculty - details of faculty of data faculty_list", "page @variables: acadTtForm - the form to add academic calender", "in database desig - get designation object of student holds_desig", "request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses':", "in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex ==", "= True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all()", "# batch - the current batch of the student #", "else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if", "from form.REQUEST batch - batch from form.REQUEST branch - branch", "contains metadata about the requested page. @variables: profiles - gets", "i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request):", "try: current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id =", "(str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data", "= AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length", "= set() unregistered_students = set() for stu in obj: registered_students.add(stu.student_id)", "Get credit details from forms and the append it to", "student to be displayed in teh webpage # \"\"\" #", "the requested page. # @variables: # sem_cred = Get credit", "desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation =", "batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses", "sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1,", "contains metadata about the requested page @variables: sem - get", "except Exception as e: examTtForm = \"\" acadTtForm = \"\"", "[int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details =", "profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value)", "- current year batch - batch form form curriculum -", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t", "Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester grade", "HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context) # ####################################", "Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): #", "{}) def deleteMinute(request): # \"\"\" # to delete an existing", "record in the database table # @variables: # e -", "requested page # @variables: # current_user - the username of", "\"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch", "\"\"\" This function generates semester grade sheet @variables: now -", "HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print (current_user) #", "= HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k = str(user_details).split()", "# print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator')", "varibles faculty - details of faculty of data faculty_list -", "- the programme the student is enrolled in # ph", "to be deleted # \"\"\" # if request.method == \"POST\":", "@variables: # e - the extraInfo objects of the student", "page # @variables: # name - the name of the", "render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return render(request,", "str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep =", "batch - gets the batch from form sem - stores", "= student.user) # designation = [] # for des in", "= Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i in", "# course - Course details which is selected by the", "subject - subject of which the grade has to be", "ofwhich the grade is added \"\"\" # if user_check(request): #", "# } # return render(request,\"ais/ais.html\", context) # else: # return", "False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\"", "- deatils of the acad admin # s - the", "HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\": # programme=request.POST['programme']", "# if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method ==", "\"\"\" This function is used to see curriculum and edit", "s.hall_no = 1 # s.room_no = \"\" # s.save() #", "courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request,", "[] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not", "str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] ==", "- holdsDesignation object to store that the particualr student is", "year = int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch =", "@variables: # name - the name of the student #", "Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no = hall #", "of student holds_desig - get hold_desig object of student currs", "be uploaded @param: request - contains metadata about the requested", "courses = Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj", "from file category - details of student from file phone_no", "list students that is a senator # hDes - the", "# } # return JsonResponse(data)# ###################################################### # # ##########Senate meeting", "# view to add attendance data to database # def", "return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request):", "request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" :", "the new convenor/coconvenor # data - data of the student", "- gets the excel file having data excel - excel", "= request.POST.get('programme') # batch = request.POST.get('batch') # ph = request.POST.get('phoneno')", "- course ofwhich the grade is added \"\"\" # if", "academic timetable objects calendar - all the academic calender objects", "##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\" #", "= request.POST.getlist('choice') # for i in choices: # course =", "= \"\" request_sem = \"\" #for checking if the user", "d[2] # sem = int(d[3]) # if request.method == \"POST\":", "False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag =", "course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1", "array to add data to variable data k -temporary array", "to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date", "return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\")", "def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam timetable.", "desig - get designation object of student holds_desig - get", "address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\":", "data excel - excel file sheet - sheet no in", "course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8]", "- the designation object that contains senator # student -", "the form to add academic calender examTtForm - the form", "desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except Exception", "variables for final output b - temporary variables for final", "a convenor CoConvenor - the extraInfo objects that holds the", "# else: # father = request.POST.get('father') # mother = request.POST.get('mother')", "# if result == \"Convenor\": # hDes.designation = s #", "timetable from the server. @param: request - contains metadata about", "HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') #", "faculty - details of faculty of data faculty_list - list", "} if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel =", "add a new senate meeting minute object to the database.", "s - designation object of Convenor # p - designation", "(Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm", "this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses =", "from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators", "date from system year - current year batch - batch", "course - course ofwhich the grade is added \"\"\" #", "request_batch = \"\" request_branch = \"\" request_programme = \"\" request_sem", "current_user - father's name of the student # user_details -", "final_user - final designation of request user \"\"\" try: current_user", "tag whether to delete it or not # course -", "request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0)", "courses in curriculum course_type - list the type of courses", "request.POST.get('batch') # ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): #", "f1,f2,f3 - temporary varibles faculty - details of faculty of", "= \"\" #for checking if the user has searched for", "senator meetings minuteForm - the form to add a senate", ": assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag } return", "- data is stored in database \"\"\" if user_check(request): return", "def float_course_submit(request): \"\"\" to float courses for the next sem", "str(user_details).split() final_user = k[2] except Exception as e: acadadmin=\"\" final_user=\"\"", "The ending date for the academic caldendar event. desc -", "Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] }", "'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return", "contains metadata about the requested page. # @variables: # choices", "= ' + batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx'", "from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader", "sem - semester of the student grade - grade to", "minute object from the database. # @param: # request -", "course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False", "= AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm =", "phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization ==", "is a convenor/coconvenor to be deleted # data - data", "datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for i in", "requested page # @variables: # name - the name of", "Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation,", "(CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views", "to_date - The ending date for the academic caldendar event.", "from_date - The starting date for the academic calendar event.", "be hidden in the webpage # \"\"\" # s =", "p = Designation.objects.get(name='Co Convenor') # if request.method == 'POST': #", "return HttpResponse('sucess') # else: # return HttpResponse('not uploaded') # return", "- final designation of request user \"\"\" try: current_user =", "calendar event. prev_desc - Description for the previous event which", "return False def get_context(request): \"\"\" This function gets basic gata", "category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem, ) desig", "request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam':", "# ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request): # \"\"\"", "Convenor # p - designation object of Co Convenor #", "of the students context - the datas to be displayed", "of the acad admin # father - father's name of", "if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for i", "request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme=", "registered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\"", "# s.mother_name = \"\" # s.hall_no = 1 # s.room_no", "in registered_students: unregistered_students.add(stu) data = [] m = 1 for", "s = get_object_or_404(Student, id=e) # data = { # 'rollno':", "the student # \"\"\" if request.method == \"POST\": name =", "+ str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl.", "@param: request - contains metadata about the requested page. @variables:", "all the courses in curriculum course_type - list the type", "[int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() except Exception", "AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list =", "contains metadata about the requested page @variables: current_user - get", "courses from database courses_type - get course types from database", "(temp) # print (current_user) # acadadmin = temp.working # k", "the database and the update it. # \"\"\" if request.method==\"POST\":", "@csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to remove a", "form.REQUEST ins - data is stored in database \"\"\" if", "'phoneno': ph, # 'batch': batch # } # print(data) #", "designation ID. # extraInfo - extraInfo object of the student", "database ans - Formatted Array to be converted to xlsx", "academic caldendar event. desc - Description for the academic calendar", "# s = Grades.objects.filter(student_id=id, sem=sem) # for p in s:", "extrainfo object created in database stud_data - new student object", "form.REQUEST now - current date from system year - current", "course_list_2 = [2, 4, 6, 8] else: course_list_2 = [1,", "\"\"\" # acadmic admin to update the additional courses #", "= int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1] else:", "= book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name + str(\"", "contains metadata about the requested page # @variables: # s", "for final output st - temporary variables for final output", "'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text", "== \"\" : logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated", "Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses", "# hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working", "the student's record in the database table # @variables: #", "- details of the user # sem - current semester", "# print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable to", "s # hDes.save() # student = Student.objects.get(id=extraInfo) # data =", "# # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s =", "the student # acadadmin - student's address # final_user -", "\"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] } return render(request,", "Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme'])", "all meeting objects held in senator meetings minuteForm - the", "the webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p =", "# } # return render(request, \"ais/ais.html\", context) # else: #", "i in to_date] to_date = datetime.datetime(*to_date).date() except Exception as e:", "is used to see curriculum and edit entries in a", "e: examTtForm = \"\" acadTtForm = \"\" calendar = \"\"", "else: return [2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\"", "ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: # data =", "'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return", "hDes.user = extraInfo.user # hDes.working = extraInfo.user # hDes.designation =", "now = datetime.datetime.now() year = int(now.year) batch = year-1 curriculum", "senate meeting minutes acadTtForm - the form to add academic", "- current datetime month - current month \"\"\" now =", "return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin to", "# } # return HttpResponseRedirect('/aims/') # # return JsonResponse(data) #", "It checkes the authentication of the user. @param: request -", "= data.split(\"-\") # id = d[0] # course = d[2]", "context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm", "timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method ==", "- all the courses in curriculum course_type - list the", "batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students =", "context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm", "from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all()", "#for checking if the user has searched for any particular", "data that contains where the student will become # convenor", "faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def", "branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else:", "credits - credits from form.REQUEST optional - optional from form.REQUEST", "# data - data of the student to be displayed", "Batch from form request_branch - Branch from form request_programme -", "request.method == 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch']", "else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required", "page # @variables: # current_user - father's name of the", "as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for", "designation as a senator students - all the objects in", "requested page @variables: senates - the extraInfo objects that holds", "file title - formatting variable of title the workbook subtitle", "student to become the convenor/coconvenor # extraInfo - extraInfo object", "request_branch = \"\" request_programme = \"\" request_sem = \"\" #for", "to set up the homepage of the application. It checkes", "# curriculum # # #################################### @login_required def curriculum(request): \"\"\" This", "return faculty_list @login_required def float_course(request): \"\"\" to float courses for", "function is used to set up the homepage of the", "# designation = des.designation.name # des.delete() # data = {", "\"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\") return render(request,", "profile picture, about me etc of a student # @param:", "p.delete() # else: # return HttpResponse(\"Unable to delete data\") return", "It deletes the grade of the student # @param: #", "about the requested page # @variables: # rollno - rollno", "outdated exam timetable. @param: request - contains metadata about the", "choices: # i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/')", ": procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' :", "datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date", "HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method == 'POST': i=0", "- Formatted Array to be converted to xlsx k -temporary", "== \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem)", "add a new student senator # @param: # request -", "# context= { # 'courses': courses, # 'course_type': course_type, #", "\"Convenor\": # hDes.designation = s # else: # hDes.designation =", "{ # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme,", "be logged in and must be acadadmin @param: request -", "to formatted array/variable output - io Bytes object to write", "import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation,", "\"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] #", "if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno =", "and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" # to", "senator # @param: # request - contains metadata about the", "not in choices: # i.acad_selection = False # i.save() #", "# It adds the advance profile information like hall no,", "from file mothers_name - details of student from file category", "in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\"", "to add a new senate meeting minute object to the", "calender objects context - the datas to be displayed in", "calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses", "sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k =", "str(room) # student.save() # s = Student.objects.get(id=student) # s.father_name=father #", "# ''' # # view to add attendance data to", "of the user. # user_details - to get the details", "request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=", "as a coconvenor meetings - the all meeting objects held", "#################################### @login_required def curriculum(request): \"\"\" This function is used to", "arr = st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu):", "form.REQUEST sem - semester from form.REQUEST course_code - course_code from", "Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the grades", "the application. It checkes the authentication of the user and", "No (in formated data) z - temporary array to add", "''' def delete_advanced_profile(request): # \"\"\" # to delete the advance", "Designation.objects.get(name='Co Convenor') # if request.method == 'POST': # rollno =", "= [] for i in obj: if i.student_id.batch_id.year == int(batch):", "# designation = [] # for des in hDes: #", "# s.room_no = \"\" # s.save() # else: # return", "Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch", "result - the data that contains where the student will", "- programme from form.REQUEST now - current date from system", "get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student, id=e) #", "existing senate meeting minute object from the database. # @param:", "get_calendar_details = Get the object of the calendar instance from", "t - Object of Exam time table to be deleted", "the student is enrolled in # ph - the phone", "= 'attachment; filename = ' + course.code + '.xlsx' response['Content-Disposition']", "convenor # c - the designation object that contains co", "if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch =", "get current semester from current time now - get current", "# s.hall_no = hall # s.room_no = room # s.save()", "'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # # return", "Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # #", "sheet.set_column('E:E',15) k = 4 num = 1 for i in", "else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch", "+ str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required", "- details of faculty of data faculty_list - list of", "metadata about the requested page @variables: request_batch - Batch from", "course curr_key - gets the curriculum from database obj -", "credit for a current semester that a student must take", "pass # if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") #", "s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") #", "the minimum credits from the database and the update it.", "# 'programme': programme, # 'phoneno': ph, # 'batch': batch #", "array to add data to formatted array/variable output - io", "@variables: acadTtForm - data of delete dictionary in post request", ") new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst)", "Exception as e: examTtForm = \"\" acadTtForm = \"\" calendar", "No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k", "# \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details =", "desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user = k[2]", "- gets the data of current user. # user_details -", "# cpi = request.POST.get('cpi') # student.address = str(hall) + \"", "# return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set", "attendance - all the attendance objects of the students context", "details of user from database desig_id - check for designation", "'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return", "sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True", "of the student # batch - the current batch of", "used to see curriculum and edit entries in a curriculum.", "stdents data from database ans - Formatted Array to be", "'s name of the student # acadadmin - student's address", "student from file hall_no - details of student from file", "- all exam timetable from database \"\"\" if user_check(request): return", "the requested page # @variables: # s - the designation", "course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return", "# } # s.delete() # e.delete() # u.delete() # return", "i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans =", "import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string", "database ins - Inster data in database \"\"\" if user_check(request):", "result = request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user =", "sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k =", "user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data = request.POST['delete']", "which is to be updated. get_calendar_details = Get the object", "'grades': grades, # 'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\",", "Registered Students @param: request - contains metadata about the requested", "@login_required def float_course(request): \"\"\" to float courses for the next", "course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option']", "generatexlsheet(request): \"\"\" to generate Course List of Registered Students @param:", "'application/vnd.ms-excel') st = 'attachment; filename = ' + course.code +", "# room = request.POST.get('room') # cpi = request.POST.get('cpi') # student.address", "z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in", "else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch", "student - the students as a senator extra - all", "Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ #", "page @variables: current_user - father's name of the student user_details", "final_user - details of the user # sem - current", "displayed in the webpage this_sem_course - tha data of thsi", "1 for i in unregistered_students: z = [] z.append(m) m", "= xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value)", "user and also fetches the available data from the databases", "displayed in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context", "return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): #", "function generates semester grade sheet @variables: now - current datetime", "metadata about the requested page. # @variables: # sem_cred =", "st return response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration", "= Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no = hall", "- optional from form.REQUEST course_type - course_type from form.REQUEST ins", "page @variables: batch - gets the batch course - gets", "= Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id = batch,", "metadata about the requested page @variables: senates - the extraInfo", "= ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm =", "- Formated data for context m - counter for Sl.", "selected by the academic admin. # \"\"\" if request.method ==", "student # acadadmin - student's address # final_user - details", "# programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses", "t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic", "\"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return", "from form request_sem - Semester from form \"\"\" if user_check(request):", "cpi = request.POST.get('cpi') # student.address = str(hall) + \" \"", "assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False)", "for a current semester that a student must take #", "# #################################### @login_required def curriculum(request): \"\"\" This function is used", "course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses = [] for course_slot", "context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This", "from file user - new user created in database einfo", "User must be logged in and must be acadadmin @param:", "form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1']", "@login_required def delete_curriculum(request): \"\"\" This function is used to delete", "that a student must take # @param: # request -", "address # final_user - details of the user # sem", "calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] }", "Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name = \"\" #", "# if request.method == 'POST': # rollno = request.POST.get('rollno_convenor') #", "course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for", "except Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) !=", "= Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() # courses", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST':", "Programme from form request_sem - Semester from form \"\"\" if", "= InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for", "Convenor - the extraInfo objects that holds the designation as", "batch - the current batch of the student # programme", "\") + batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2',", "subject of which the grade has to be added sem", "file first_name - details of student from file last_name -", "the page. @param: request - contains metadata about the requested", "courses for the next sem and store data in databsae.", "# rollno, etc of a student # @param: # request", "all timetable from database exam_t - all exam timetable from", "- gets the batch from form sem - stores the", "verify_grade(request): \"\"\" It verify the grades of the student @param:", "# user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk')", "= Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try:", "\"\"\" # It deletes the grade of the student #", ": \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle)", "extraInfo.user # hDes.working = extraInfo.user # if result == \"Convenor\":", "to the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar", "store that the particualr student is # holding the convenor/coconvenor", "= name.upper() # db.id = roll # db.batch = batch", "request_batch == \"\" and request_branch == \"\" and request_programme==\"\" and", "in user # user_details - the details of the current", "batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme)", "the webpage this_sem_course - tha data of thsi semester courses", "\"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval =", "# for i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first()", "ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST,", "@login_required def add_new_profile (request): \"\"\" To add details of new", "<= 12: return [1, 3, 5, 7] else: return [2,", "student's address # final_user - details of the user #", "i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme']", "in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= {", "- the student object from the requested rollno # \"\"\"", "\"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name", "return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method ==", "ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from", "if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student =", "sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code')", "student's record in the database table # @variables: # e", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] }", "in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits,", "# acadadmin - deatils of the acad admin # father", "\"\"\" to update an entry to the academic calendar to", "# courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # context=", "else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for", "requested page # @variables: # data - the id of", "hold_desig object of student currs - get curriculum details reg", "- details of student from file hall_no - details of", "requested page # @variables: # current_user - father's name of", "print (temp) # print (current_user) # acadadmin = temp.working #", "the username of the logged in user # user_details -", "acadTtForm = AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm", "c - temporary variables for final output st - temporary", "return render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update", "\"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student =", "of student from file mothers_name - details of student from", "# desig_id - mother 's name of the student #", "an array. # sem - Get the object for the", "title the workbook subtitle - formatting variable of subtitle the", "= extraInfo.user # if result == \"Convenor\": # hDes.designation =", "sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60)", "the student # add - student's address # cpi -", "\"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can upload the", "that holds the designation as a coconvenor meetings - the", "requested page # pk - the primary key of the", "in the webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\")", "in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu", "{ # 'id': pk, # 'designation': designation, # } #", "current_user - father's name of the student user_details - the", "of user. It checkes the authentication of the user. @param:", "meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\" # to", "courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable =", "examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar =", "z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext)", "m = 1 for i in unregistered_students: z = []", "return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student basic profile##################", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm hone wala", "Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\",", "curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user,", "s = Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name =", "JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\" # to", "response @login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report after", "= { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation':", "= d[2] # sem = int(d[3]) # if request.method ==", "- the primary key of that particular student field #", "= MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return", "if request.method == 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i)", "def add_exam_timetable(request): \"\"\" acad-admin can upload the exam timtable of", "def add_calendar(request): \"\"\" to add an entry to the academic", "the particualr student is # holding the convenor/coconvenor designation #", "in excel file roll_no - details of student from file", "requested page. @variables: from_date - The starting date for the", "sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type =", "@login_required def next_curriculum(request): \"\"\" This function is used to decide", "if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) #", "HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "return render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2'] }", "for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch", "first_name - details of student from file last_name - details", "page # @variables: # current_user - gets the data of", "request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db = Student() #", "from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request)", "- stores the next semester obj - All the registration", "of faculty of data faculty_list - list of faculty \"\"\"", ") sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots", "= hall # s.room_no = room # s.save() # return", "request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def", "curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" # to delete", "= obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except Exception", "# 'rollno': pk, # } # s.delete() # e.delete() #", "add an entry to the academic calendar to be uploaded", "designation of the user. # user_details - to get the", "Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username, # 'rollno':", "get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk')", "of the student to be displayed in the webpage #", "render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete", "it or not # course - get the course details", "is # holding the convenor/coconvenor designation # student - the", "'-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def add_new_profile (request):", "that is a senator # hDes - the holdDesignation object", "\"\" request_programme = \"\" if request_batch == \"\" and request_branch", "in teh webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username)", "specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des =", "extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name", "this_sem_courses = \"\" next_sem_courses = \"\" courses = \"\" course_type", "for i in to_date] to_date = datetime.datetime(*to_date).date() except Exception as", "\"\"\" to generate preresgistration report after pre-registration @param: request -", "courses # @param: # request - contains metadata about the", "Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades':", "m - counter for Sl. No (in formated data) z", "sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1", "# \"\"\" # It adds the advance profile information like", "data - tag whether to delete it or not #", "'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST: try:", "= temp.working k = str(user_details).split() final_user = k[2] except Exception", "file department - details of student from file specialization -", "Branch from form request_programme - Programme from form request_sem -", "@csrf_exempt def senator(request): # \"\"\" # to add a new", "@variables: data - data of delete dictionary in post request", "HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == 'POST': try:", "# \"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor')", "file sex - details of student from file title -", "username = e.user.username) # s = get_object_or_404(Student, id=e) # data", "# if request.method == 'POST' and request.FILES: # form =", "= ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation()", ": procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' :", "or coconvenor # hDes - holdsDesignation object to store that", "data from the databases to display it on the page.", "# form.save() # return HttpResponse('sucess') # else: # return HttpResponse('not", "context) # else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\")", "and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if", "4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to generate Course", "if request.method == \"POST\": # data = request.POST['delete'] # t", "a convenor/coconvenor to be deleted # data - data of", "courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar':", "choices = request.POST.getlist('choice') # for i in choices: # course", "from database obj - get stdents data from database ans", "to the database. # @param: # request - contains metadata", "s.room_no = \"\" # s.save() # else: # return HttpResponse(\"Data", "be converted to xlsx k -temporary array to add data", "obj.account_status except Exception as e: examTtForm = \"\" acadTtForm =", "form required to add exam timetable Dean - the extraInfo", "= Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except", "database for the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "= ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses =", "= datetime.datetime.now() month = int(now.month) if month >= 7 and", "entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch", "= [] for i in registered_courses: k = [] k.append(i.student_id.id.id)", "@login_required def verify_grade(request): \"\"\" It verify the grades of the", "course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits,", "form.REQUEST branch - branch from form.REQUEST sem - semester from", "@variables: programme - programme from form.REQUEST now - current date", "from form.REQUEST ins - data is stored in database \"\"\"", "- the students as a senator extra - all the", "except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\",", "ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor')", "+ \" \" + str(room) # student.save() # s =", "- list the type of courses \"\"\" if user_check(request): return", "batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] ==", "rollno of the student to become the convenor/coconvenor # extraInfo", "objects that holds the designation as a convenor CoConvenor -", "= ph # db.save() # st.save() # data = {", "AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) #", "= temp.working # k = str(user_details).split() # print(k) # final_user", "return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete", "from forms and the append it to an array. #", "page # @variables: # s - the designation object that", "to delete an existing senate meeting minute object from the", "def sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet @variables:", "# return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt", "# for i in choices: # course = Course.objects.all().filter(course_id=i).first() #", "- the current batch of the student # programme -", "HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted Successfully\") def", "course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False", "get the details of the required user. # \"\"\" #", "pk - the primary key of that particular student field", "xlrd import logging from io import BytesIO from xlsxwriter.workbook import", "homepage(request): \"\"\" This function is used to set up the", "acadTtForm - data of delete dictionary in post request timetable", "Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method", "get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username = e.user.username) #", "first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else:", "True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat", "searched for any particular curriculum if request_batch == \"\" and", "# if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if", "function is used to check the type of user. It", "Student.objects.filter(id=roll).exists(): # db = Student() # st = ExtraInfo.objects.get(id=roll.id) #", "hod_flag, 'account_flag' : account_flag } return context @login_required def homepage(request):", "page. # @variables: # sem_cred = Get credit details from", "== 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for", "- the User object of the student # s -", "context) @login_required def add_curriculum(request): \"\"\" This function is used to", "# data = { # 'id': pk, # 'designation': designation,", "user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context=", "to database # def curriculum(request): # ''' def delete_advanced_profile(request): #", "semester from current time now - get current time year", "rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details =", "= object to save new event to the academic calendar.", "\"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It", "'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False,", "deatils of the acad admin # father - father's name", "current_user - the username of the logged in user #", "variables for final output st - temporary variables for final", "programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional']", "from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc", "@variables: # current_user - father's name of the student #", "'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True,", "True # course.save() # courses = Course.objects.all() # for i", "\"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): #", "workbook subtitle - formatting variable of subtitle the workbook normaltext", "= \"\" next_sem_courses = \"\" courses = \"\" course_type =", "return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin can", "import get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf import", "meeting minutes acadTtForm - the form to add academic calender", "str(hall) + \" \" + str(room) # student.save() # s", "student - the student object of the new convenor/coconvenor #", "of the student # roll - the rollno of the", "convenor/coconvenor # data - data of the student to be", "print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno'))", ": logging.warning(\"No faculty\") else: flot = Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True", "the registration details appended into one data - Formated data", "e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list = [] for", "# s.father_name = \"\" # s.mother_name = \"\" # s.hall_no", "else: # hDes.designation = p # hDes.save() # data =", "list from database @param: request - contains metadata about the", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context)", "delete dictionary in post request t - Object of time", "admin to update the additional courses # @param: # request", "student field # @variables: # s - the designation object", "the student # programme - the programme the student is", "specialization == \"\": specialization=\"None\" if hall_no == None: hall_no=3 else:", "now - get current time year - getcurrent year batch", "an entry to the academic calendar to be updated. @param:", "= True).filter(hod_approval =True).filter(hod_approval = True) assistant_list_length = len(assistant_list.filter(acad_approval = False))", "- contains metadata about the requested page. # @variables: #", "branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses", "context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list': faculty_list,", "== 'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES) #", "- all the academic calender objects context - the datas", "# if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for", "file hall_no - details of student from file programme -", "i in courses: # if i.course_id not in choices: #", "k = 4 num = 1 for i in ans:", "data = request.POST['delete'] # d = data.split(\"-\") # id =", "acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True else:", "# return JsonResponse(data) # else: # data = {} #", "curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades = Grades.objects.filter(curriculum_id=curr_course) # context= {", "grade sheet @variables: now - current datetime month - current", "object from the requested rollno # \"\"\" current_user = get_object_or_404(User,", "excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value)", "import logging from io import BytesIO from xlsxwriter.workbook import Workbook", "if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor(", "context={ 'tab_id' :['3','1'] } if request.method == 'POST': try: id=request.POST['id']", "from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for", "\"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc =", "to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request):", "function is used to edit curriculum in database It checkes", "of the student required to check if the student is", "i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True,", "title - formatting variable of title the workbook subtitle -", "academic calendar event. to_date - The ending date for the", "request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses' :", "the student to be hidden in the webpage # \"\"\"", "m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output", "sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj", "from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar,", "ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() #", "of time table to be deleted \"\"\" if user_check(request): return", "sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15)", "' + batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition']", "# information that the particular student is a convenor/coconvenor to", "render(request, \"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\") return", "cpi # hall - hall no of where the student", "sem - semester from form.REQUEST course_code - course_code from form.REQUEST", "faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to float courses", "= HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) # print (current_user)", "form.REQUEST course_name - course-name from form.REQUEST course_id - course_id from", "str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st return response @login_required def", "- student's address subject - subject of which the grade", "- the form to add academic calender examTtForm - the", "= acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar", "form.REQUEST batch - batch from form.REQUEST branch - branch from", "in the college attendance - all the attendance objects of", "1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2]", "if request.method == \"POST\": pass # print(request.POST) # choices =", "the programme the student is enrolled in # ph -", "# return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\"", "json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request,", "= True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark", "\"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as", "details of the current user. # desig_id - to check", "False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet()", "admin # father - father's name of the student #", "in the database table # @variables: # e - the", "from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i)", "- all the attendance objects of the students context -", "about the requested page. # @variables: # choices - selected", "- details of the current user. # desig_id - to", "view_course(request): # if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch']", "= i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst,", "= Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status hod_flag", "BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22,", "can upload the time table(any type of) of the semester.", "'course_type' : course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1']", "batch.name + batch.discipline.acronym + str(batch.year) + '-preresgistration.xlsx' response['Content-Disposition'] = st", "i in range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0])", "the primary key of the student's record in the database", "# \"\"\" # to set minimum credit for a current", "the extraInfo objects that holds the designation as a dean", "sem - current semester of the student # data -", "'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context= { 'tab_id'", "# return render(request,\"ais/ais.html\", context) # else: # return HttpResponseRedirect('/aims/') return", "the student course - course ofwhich the grade is added", "request_branch - Branch from form request_programme - Programme from form", "7] else: return [2, 4, 6, 8] @login_required def generatexlsheet(request):", "# hDes.designation = p # hDes.save() # data = {", "# context= { # 'grades': grades, # 'tab_id' :\"2\" #", "into one data - Formated data for context m -", "= batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id)", "s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user =", "sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4", "if request.method == 'POST' and request.FILES: # form = MinuteForm(request.POST,", "# father - father's name of the student # rollno", "name of the student # add - student's address #", "# @csrf_exempt def senator(request): # \"\"\" # to add a", "requested page. @variables: acadTtForm - data of delete dictionary in", "the available data from the databases to display it on", "new student senator # @param: # request - contains metadata", "z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title =", "add academic calender examTtForm - the form required to add", "This function is used to see curriculum and edit entries", "curriculum and edit entries in a curriculum. It checkes the", "type of user. It checkes the authentication of the user.", "- semester of the student grade - grade to be", "def add_new_profile (request): \"\"\" To add details of new upcoming", "of request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details", "unregistered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\"", "programme, # 'phoneno': ph, # 'batch': batch # } #", "from form.REQUEST sem - semester from form.REQUEST course_code - course_code", "Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print", "Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type", "registered_courses = [] for i in obj: if i.student_id.batch_id.year ==", "of the student # rollno - the rollno of the", "= from_date[0].split('-') from_date = [int(i) for i in from_date] from_date", "else: # return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data", "faculty_list - list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name", ":['10','1'] } acadTtForm = AcademicTimetableForm() if request.method == 'POST' and", "= AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context)", "{ 'tab_id' :['2','1'] } if request.method == 'POST' and request.FILES:", "branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch =", "} examTtForm = ExamTimetableForm() if request.method == 'POST' and request.FILES:", "student from file first_name - details of student from file", "mother's name of the student # add - student's address", "batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students", "file phone_no - details of student from file address -", "previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all()", "HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") #", "academic admin. # \"\"\" if request.method == \"POST\": pass #", "batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass", "= Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent =", "user from database desig_id - check for designation acadadmin -", "MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo,", "= book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text,", "user_details - extract details of user from database desig_id -", ":['5','1'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "'tab_id' :['2','1'] } if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles']", "the requested page. @variables: acadTtForm - data of delete dictionary", "academic calendar to be uploaded @param: request - contains metadata", "edit_curriculum(request): \"\"\" This function is used to edit curriculum in", "file category - details of student from file phone_no -", "range(1, 10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for", "data of the student to be displayed in the webpage", "displayed in teh webpage # \"\"\" # current_user = get_object_or_404(User,", "data of current user. # user_details - gets the details", "to check the type of user. It checkes the authentication", "Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course) except Exception", "about the requested page # @variables: # data - the", "= str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext)", "context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if request.method ==", "timetable objects calendar - all the academic calender objects context", "deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id'", "from the database # @param: # request - contains metadata", "exam_t - all the exam timetable objects timetable - all", "def view_course(request): # if request.method == \"POST\": # programme=request.POST['programme'] #", "- details of student from file phone_no - details of", "in course_slots: courses += course_slot.courses.all() new_reg=[] for c in courses:", "= request.POST.get('father') # mother = request.POST.get('mother') # add = request.POST.get('address')", "# Deletes the student from the database # @param: #", "- the details of the current user # desig_id -", "= [] for i in faculty: faculty_list.append(i) return faculty_list @login_required", "data k -temporary array to add data to formatted array/variable", "@variables: # current_user - gets the data of current user.", "Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\"", "# return JsonResponse(data) # @csrf_exempt def deleteConvenor(request, pk): # \"\"\"", "students in the database.User must be logged in and must", "and request_branch == \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all()", "to add a new student senator # @param: # request", "of the student to be hidden in the webpage #", "the authentication of the user and also fetches the available", "calendar to be uploaded @param: request - contains metadata about", "where the student stays # room no - hostel room", "else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch =", "s # else: # hDes.designation = p # hDes.save() #", "str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\")", "objects of the student # user - the User object", "return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "the advance profile information like hall no, room no, #", "programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, )", "s or des.designation == c: # designation = des.designation.name #", "credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2':", "@param: # request - contains metadata about the requested page", "= Get the object of the calendar instance from the", "= False)) assis_stat = Assistantship_status.objects.all() for obj in assis_stat: assistant_flag", "and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem) ==", "Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type,", "procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year'", "curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context)", "book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name + str(\" \")", "'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } # return JsonResponse(data)", "etc of a student # @param: # request - contains", "data = {} # return JsonResponse(data) # else: # father", "if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch']", "# hDes = get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete()", "== s or des.designation == c: # designation = des.designation.name", "subtitle the workbook normaltext - formatting variable for normal text", "get the course details # \"\"\" # current_user = get_object_or_404(User,", "student is a senator # \"\"\" pass # if request.POST:", "t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request):", "db.name = name.upper() # db.id = roll # db.batch =", "form database ins - Inster data in database \"\"\" if", "current month \"\"\" now = datetime.datetime.now() month = int(now.month) if", "courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # context= {", "# sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def", "curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) # grades =", "s.mother_name = \"\" # s.hall_no = 1 # s.room_no =", "\"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function", "return HttpResponseRedirect('/academic-procedures/') timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= {", "page. # @variables: # choices - selected addtional courses by", "programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses =", "io Bytes object to write to xlsx file book -", "credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum", "@variables: now - current datetime month - current month \"\"\"", ") new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch =", "@login_required def add_calendar(request): \"\"\" to add an entry to the", "import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status", "webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return", "sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30)", "data about curriculum from database courses - get courses from", "temporary variables for final output st - temporary variables for", "view to add attendance data to database # def curriculum(request):", "This function is used to check the type of user.", "if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno)", "render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes the", "table to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if", "picture, about me etc of a student # @param: #", "programme - programme from form.REQUEST now - current date from", "- list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name =", "details of student from file sex - details of student", "request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch", "user_details - the details of the current user # desig_id", "Student class Convenor - the extraInfo objects that holds the", "from the server. @param: request - contains metadata about the", "= {} # return JsonResponse(data) # else: # data =", "os import xlrd import logging from io import BytesIO from", "used to edit curriculum in database It checkes the authentication", "\"ais/ais.html\") def delete_grade(request): # \"\"\" # It deletes the grade", "subtitle - formatting variable of subtitle the workbook normaltext -", "curr_key=\"\" obj=\"\" registered_courses = [] for i in obj: if", "sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list", "'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list,", "Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() #", "designation object of student holds_desig - get hold_desig object of", "received from id to be deleted # \"\"\" # if", "database to send to template @param: request - contains metadata", "about the requested page. @variables: data - data of delete", "= Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name = \"\"", "Course as Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import", "departments in the college attendance - all the attendance objects", "z = [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name))", "request.POST['delete'] # d = data.split(\"-\") # id = d[0] #", ": procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' :", "else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\"", "data = {} # return JsonResponse(data) # else: # data", "a senator # \"\"\" pass # if request.POST: # s", "timetable = \"\" exam_t = \"\" pass context = {", "- contains metadata about the requested page # @variables: #", "###################################################### # # ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request):", ") sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year,", "not # course - get the course details # \"\"\"", "instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request,", "entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme=", "applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline)", "t - Object of time table to be deleted \"\"\"", "HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum,", "courses next_sem_courses - the data of next semester courses courses", "write to xlsx file book - workbook of xlsx file", "z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered')", "# user_details - gets the details of the required user.", "deleted # t - the minute object received from id", "= Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print", "procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' :", "} if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum", "k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True}) title", "s.father_name=father # s.mother_name=mother # s.hall_no = hall # s.room_no =", "batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins)", "upcoming students in the database.User must be logged in and", "(\"Pre-registeration : \"+ batch.name + str(\" \") + batch.discipline.acronym +", "of the calendar instance from the database for the previous", "form.REQUEST optional - optional from form.REQUEST course_type - course_type from", "the # information that the particular student is a senator", "- student's cpi # hall - hall no of where", "next_sem_courses = \"\" courses = \"\" course_type = \"\" timetable", "of the student grade - grade to be added in", "- details of student from file address - details of", "\"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" # to delete an", "{ 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] }", "the outdated timetable from the server. @param: request - contains", "hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name,", "father's name of the student # user_details - the rollno", "a student must take # @param: # request - contains", "\"\" # s.mother_name = \"\" # s.hall_no = 1 #", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST,", "import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts", "return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def", "= \"\" # s.mother_name = \"\" # s.hall_no = 1", "objects timetable - all the academic timetable objects calendar -", "extraInfo.id, # 'designation': hDes.designation.name, # } # return JsonResponse(data) #", "Get the object for the minimum credits from the database", "primary key of the student's record in the database table", "function is used to see curriculum and edit entries in", "str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext)", "JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes", "profile information like username,password, name, # rollno, etc of a", "the user has searched for any particular curriculum if request_batch", "request.method == \"POST\": # print(\"confirm hone wala hai\") # print(request.POST)", "details of student from file user - new user created", "object created in database desig - get designation object of", "= Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if request.method", "for i in choices: # course = Course.objects.all().filter(course_id=i).first() # course.acad_selection", "in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else:", "year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option']", "# @param: # request - contains metadata about the requested", "to add a senate meeting minutes acadTtForm - the form", "new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else:", "return [1, 3, 5, 7] else: return [2, 4, 6,", "html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context)", "new senator # data - data of the student to", "@variables: # current_user - the username of the logged in", "the data of current user. # user_details - gets the", "context) else: context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\",", "used to delete curriculum entry in database It checkes the", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course =", "in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4])", "user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no", "if request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s =", "sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle)", "HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request): #", "get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) # designation", "= AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses =", "email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value", "the academic calendar event. prev_desc - Description for the previous", "Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch", "update an entry to the academic calendar to be updated.", "from form sem - stores the next semester obj -", "def senator(request): # \"\"\" # to add a new student", "entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save()", "def deleteSenator(request, pk): # \"\"\" # to remove a senator", "= desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user =", "current user # acadadmin - deatils of the acad admin", "HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader import", "for c in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data", "if request_batch == \"\" and request_branch == \"\" and request_programme==\"\"", "for the previous Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar", "= \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark =", "'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else:", "is available # desig_id - mother 's name of the", "calendar to be updated. @param: request - contains metadata about", "} if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch", "# return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin", "student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return", "render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request): # \"\"\" #", "of the new convenor/coconvenor # data - data of the", "student # add - student's address # cpi - student's", "academic calender objects department - all the departments in the", "form request_sem - Semester from form curriculum - Get data", "= str(user_details).split() # print(k) # final_user = k[2] # if", "# \"\"\" if request.method == \"POST\": pass # print(request.POST) #", "= MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() # return", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2", "student object of the new convenor/coconvenor # data - data", "HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method == \"POST\":", "'programme': programme, # 'phoneno': ph, # 'batch': batch # }", "course_type - list the type of courses \"\"\" if user_check(request):", "requested page. @variables: profiles - gets the excel file having", "from_date = from_date[0].split('-') from_date = [int(i) for i in from_date]", "context) @login_required def float_course_submit(request): \"\"\" to float courses for the", "become the convenor/coconvenor # extraInfo - extraInfo object of the", "acadadmin - deatils of the acad admin # s -", "request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) #", "# s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo, id=request.POST.getlist(\"senate_id\")[0])", "= {} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk):", "No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15)", "checking if the user has searched for any particular curriculum", ": course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1'] #", "print (current_user) # acadadmin = temp.working # k = str(user_details).split()", "delete_advanced_profile(request): # \"\"\" # to delete the advance information of", "<reponame>29rj/Fusion<gh_stars>10-100 import datetime import json import os import xlrd import", "of delete dictionary in post request t - Object of", "context={ 'tab_id' :['3','2'] } if request.method == 'POST': i=0 new_curr=[]", "curriculum(request): \"\"\" This function is used to see curriculum and", "be rendered titletext - formatting variable of title text dep", "be added sem - semester of the student grade -", "from system year - current year batch - batch form", "room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def", "workbook of xlsx file title - formatting variable of title", "elif request.POST['option'] == '2': new_curriculum=[] for i in curriculum: ins=Curriculum(", "requested page # @variables: # s - the designation object", "# else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): #", "get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor(", "deletes the grade of the student # @param: # request", "# this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses", "str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close()", "datetime.datetime.now() year = int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch", "request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in", "\"\": specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme']", "course = d[2] # sem = int(d[3]) # if request.method", "held in senator meetings minuteForm - the form to add", "\"\"\" # to remove a convenor/coconvenor from the position #", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if", "course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() #", "the database table # @variables: # e - the extraInfo", "course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)]", "for i in unregistered_students: z = [] z.append(m) m +=", "= False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(hod_approval", "of the student # programme - the programme the student", "# s.mother_name=mother # s.hall_no = hall # s.room_no = room", "ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department,", "programme # st.phone_no = ph # db.save() # st.save() #", "pk): # \"\"\" # to remove a senator from the", "InitialRegistration, course_registration, AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo)", "\"\"\" # to delete an existing senate meeting minute object", "- all the objects in the Student class Convenor -", "= request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context=", "the student is available # mother - mother's name of", "= get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id =", "request_programme = \"\" if request_batch == \"\" and request_branch ==", "webpage # \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c =", "get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save()", "student # rollno - the rollno of the student required", "get_context(request) return render(request, \"ais/ais.html\", context) # #################################### # # curriculum", "# s - designation object of Convenor # p -", "'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme =", "object of the calendar instance from the database for the", "context= { # 'grades': grades, # 'tab_id' :\"2\" # }", "current year batch - batch form form curriculum - curriculum", "u.delete() # return JsonResponse(data)# ######################################################### # ''' # # view", "} # return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else:", "= request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date =", "of delete dictionary in post request timetable - all timetable", "if month >= 7 and month <= 12: return [1,", "# 'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\", context)", "with that rollno # s - designation object of Convenor", "desig_id).first() # print (temp) # print (current_user) # acadadmin =", "- all timetable from database exam_t - all exam timetable", "\"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext)", "\"\"\" if request.method == \"POST\": name = request.POST.get('name') # roll", "HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch", "of the current user. # desig_id - to check the", "user from request user_details - extract details of user from", "student from file department - details of student from file", "context) @login_required def delete_curriculum(request): \"\"\" This function is used to", "= AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True)", "context={ 'tab_id' :['3','1'] } if request.method == \"POST\": dele =", "'POST' and request.FILES: # form = MinuteForm(request.POST, request.FILES) # if", "the requested page @variables: request_batch - Batch from form request_branch", "to xlsx file book - workbook of xlsx file title", "variable of title the workbook subtitle - formatting variable of", "def get_context(request): \"\"\" This function gets basic gata from database", "in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = []", "# 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, #", "= [] # sem_cred.append(0) # for i in range(1, 10):", "pk): # \"\"\" # Deletes the student from the database", "output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch']", "= course_registration.objects.all().filter(course_id = course) except Exception as e: batch=\"\" course=\"\"", "hDes.working = extraInfo.user # if result == \"Convenor\": # hDes.designation", "# \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first()", "curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list,", "user. # desig_id - used to check the designation ID.", "user. It checkes the authentication of the user. @param: request", "= Calendar.objects.all() context= { 'academic_calendar' :calendar, 'tab_id' :['4','1'] } if", "z - temporary variables for final output b - temporary", "# rollno - rollno of the student to become the", "in post request t - Object of Exam time table", "HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print (current_user) # acadadmin", "deatils of the acad admin # s - the student", "# p = Designation.objects.get(name='Co Convenor') # if request.method == 'POST':", "curriculum if request_batch == \"\" and request_branch == \"\" and", "ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type,", "6, 8] else: course_list_2 = [1, 3, 5, 7] #", "data being deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return render(request,", "# examTtForm = ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar", "entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type", "# if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno", "= hall_no, specialization = specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student')", "def add_convenor(request): # \"\"\" # to add a new student", "= str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep", "class Convenor - the extraInfo objects that holds the designation", "next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type", "# return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## #", "the previous event which is to be updated. get_calendar_details =", "'programme': student.programme, # 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/')", "# s = get_object_or_404(Student, id=e) # data = { #", "the student object with the given pk # hDes -", "object of student holds_desig - get hold_desig object of student", "return JsonResponse(data) # else: # father = request.POST.get('father') # mother", "the extraInfo objects that holds the designation as a coconvenor", "'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25)", "f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e:", "1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2]", "'tab_id' :['3','1'] } if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme']", "courses += course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id", "if request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date =", "acadadmin = temp.working # k = str(user_details).split() # print(k) #", ").value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no ==", "sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)]", "# @csrf_exempt def deleteSenator(request, pk): # \"\"\" # to remove", "AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else:", "file last_name - details of student from file email -", "to check the designation ID. # extraInfo - extraInfo object", "mother 's name of the student # acadadmin - student's", "field # @variables: # s - the designation object that", "objects of the students context - the datas to be", "branch - branch from form.REQUEST sem - semester from form.REQUEST", "Deleted\") @login_required def add_calendar(request): \"\"\" to add an entry to", "= \"\" courses = \"\" course_type = \"\" timetable =", "This function is used to set up the homepage of", "new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i in", "students = Student.objects.filter(batch_id = batch_id) for stu in students: if", "\"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float courses for", "return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk): # \"\"\" #", "batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, )", "@csrf_exempt def add_convenor(request): # \"\"\" # to add a new", "import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable,", "'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag'", "array/variable output - io Bytes object to write to xlsx", "sem = sem_for_generate_sheet() now = datetime.datetime.now() year = int(now.year) if", "metadata about the requested page # @variables: # data -", "in the webpage this_sem_course - tha data of thsi semester", "of Exam time table to be deleted \"\"\" if user_check(request):", "in # ph - the phone number of the student", "data to variable data k -temporary array to add data", "gets the batch course - gets the course curr_key -", "if not Student.objects.filter(id=roll).exists(): # db = Student() # st =", "data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\")", "== 'POST': i=0 new_curr=[] while True: if \"semester_\"+str(i) in request.POST:", "add data to formatted array/variable output - io Bytes object", "request - contains metadata about the requested page. @variables: from_date", "additional courses # @param: # request - contains metadata about", "gets the course curr_key - gets the curriculum from database", "designation of request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username)", "course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id = course)", "except Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list", "= batch, father_name = fathers_name, mother_name = mothers_name, cpi =", "= Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme =", "gets the excel file having data excel - excel file", "= sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request): #", "senator # \"\"\" pass # if request.POST: # s =", "3, 5, 7] # examTtForm = ExamTimetableForm() # acadTtForm =", "render(request, \"ais/ais.html\", context) @login_required def update_calendar(request): \"\"\" to update an", "new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\",", "\"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice') # for", "pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\")", "True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold':", "delete dictionary in post request timetable - all timetable from", "\"\" exam_t = \"\" pass context = { 'acadTtForm': acadTtForm,", "must be acadadmin @param: request - contains metadata about the", "data.split(\"-\") # id = d[0] # course = d[2] #", "if request.method == 'POST': try: request_batch = request.POST['batch'] request_branch =", "post request timetable - all timetable from database exam_t -", "title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Status',subtitle) sheet.set_column('A:A',20)", "# data = request.POST['delete'] # d = data.split(\"-\") # id", "details of the user # sem - current semester of", "the next sem and store data in databsae. User must", "'tab_id' :['4','1'] } if request.method == \"POST\": try: from_date =", "request_sem - Semester from form curriculum - Get data about", "ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst,", "dictionary in post request t - Object of Exam time", "[] for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for", "# print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if", "# courses = Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable", "return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add an", "metadata about the requested page @variables: current_user - father's name", "'tab_id' :['3','1'] # } courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "\"\" next_sem_courses = \"\" courses = \"\" course_type = \"\"", "for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name", "} return render(request, \"ais/ais.html\", context) else: context= { 'tab_id' :['3','2']", "title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data", "} # print(data) # return JsonResponse(data) # else: # data", "'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\",", "form.save() # return HttpResponse('sucess') # else: # return HttpResponse('not uploaded')", "int(batch): registered_courses.append(i) ans = [] for i in registered_courses: k", "save new event to the academic calendar. \"\"\" if user_check(request):", "designation = des.designation.name # des.delete() # data = { #", "def add_optional(request): # \"\"\" # acadmic admin to update the", "= roll # db.batch = batch # db.programme = programme", "an entry to the academic calendar to be uploaded @param:", "t - the minute object received from id to be", "the datas to be displayed in the webpage \"\"\" if", "courses - all the courses in curriculum course_type - list", "# \"\"\" if request.method == \"POST\": name = request.POST.get('name') #", "z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students:", "object to store that the particualr student is # holding", "examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable':", "# @csrf_exempt def add_basic_profile(request): # \"\"\" # It adds the", "file batch - details of student from file user -", "= Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\"", "= ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle)", "This function is used to delete curriculum entry in database", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method ==", "that the particular student is a senator # \"\"\" pass", "\"\" this_sem_courses = \"\" next_sem_courses = \"\" courses = \"\"", "= Calendar.objects.all() # this_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True)", "sem=sem, course_code=course_code, course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break", "available # desig_id - mother 's name of the student", "the current batch of the student # programme - the", "meeting minute object from the database. # @param: # request", "be deleted # \"\"\" # if request.method == \"POST\": #", "the student from the database # @param: # request -", "minuteForm - the form to add a senate meeting minutes", "get designation object of student holds_desig - get hold_desig object", "z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book", "batch of the student # programme - the programme the", "ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1", "desig_id - used to check the designation ID. # extraInfo", "# print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno)", "the object for the minimum credits from the database and", ":curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else: context=", "the grade of the student # @param: # request -", "# next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type", "that the particualr student is # holding the convenor/coconvenor designation", "book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle =", "= \"\" if request_batch == \"\" and request_branch == \"\"", "'designation': designation, # } # return JsonResponse(data)# ###################################################### # #", "HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors", "courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1):", "get curriculum details reg - create registeration object in registeration", "= 'attachment; filename = ' + batch.name + batch.discipline.acronym +", "'account_flag' : account_flag } return context @login_required def homepage(request): \"\"\"", "is a senator # \"\"\" pass # if request.POST: #", "try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0]", "event which is to be updated. get_calendar_details = Get the", "Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import", "having data excel - excel file sheet - sheet no", "getcurrent year batch - gets the batch from form sem", "= extraInfo.user # hDes.working = extraInfo.user # if result ==", "ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c)", "the designation as a coconvenor meetings - the all meeting", "= Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1']", "'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag'", "return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id =", "request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)]", "year batch - gets the batch from form sem -", "month \"\"\" now = datetime.datetime.now() month = int(now.month) if month", "else: # data = {} # return JsonResponse(data) # @csrf_exempt", "page @variables: programme - programme from form.REQUEST batch - batch", "converted to xlsx k -temporary array to add data to", "hostel room no # \"\"\" current_user = get_object_or_404(User, username=request.user.username) #", "request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all()", "'name': name, # 'rollno': roll.id, # 'programme': programme, # 'phoneno':", "} # s.delete() # e.delete() # u.delete() # return JsonResponse(data)#", "course.code + '.xlsx' response['Content-Disposition'] = st return response @login_required def", "request.POST.get('programme') # batch = request.POST.get('batch') # ph = request.POST.get('phoneno') #", "'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm()", "# s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no", "title = book.add_format({'bold': True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'})", "details of student from file department - details of student", "the primary key of that particular student field # @variables:", "displayed in the webpage # \"\"\" s = Designation.objects.get(name='Convenor') #", "all the academic calender objects department - all the departments", "context = get_context(request) return render(request, \"ais/ais.html\", context) # #################################### #", "form.is_valid(): # form.save() # return HttpResponse('sucess') # else: # return", "else: # father = request.POST.get('father') # mother = request.POST.get('mother') #", "# \"\"\" # s = get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation,", "programme from form.REQUEST now - current date from system year", "- get the course details # \"\"\" # current_user =", "webpage # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details", "import os import xlrd import logging from io import BytesIO", "the student object of the new convenor/coconvenor # data -", "senator # hDes - the holdDesignation object that stores the", "= request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={ # 'courses'", "\"\"\" This function gets basic gata from database to send", "# choices - selected addtional courses by the academic person.", "curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return", "\"\"\" # to add a new student convenor/coconvenor # @param:", "print(data) # return JsonResponse(data) # else: # data = {}", "Course details which is selected by the academic admin. #", "calendar - all the academic calender objects context - the", "of student from file dob - details of student from", "4 num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1", "admin # s - the student object from the requested", "# arr = st.split(\"-\") # stu = arr[0] # if", "book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold': True, 'font_size': 22, 'align':", "#return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\",", "- details of student from file dob - details of", "Get data about curriculum from database courses - get courses", "designation object that contains convenor # c - the designation", "request - contains metadata about the requested page @variables: sem", "get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch = request.POST['batch']", "hDes.designation = s # hDes.save() # student = Student.objects.get(id=extraInfo) #", "the details of the required user. # desig_id - used", "of Registered Students @param: request - contains metadata about the", "def get_faculty_list(): \"\"\" to get faculty list from database @param:", "a convenor/coconvenor from the position # @param: # request -", "from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration,", "@csrf_exempt def add_basic_profile(request): # \"\"\" # It adds the basic", "file address - details of student from file department -", "# if form.is_valid(): # form.save() # return HttpResponse('sucess') # else:", "= [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() except", "Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp)", "for p in s: # if (str(p.course_id) == course): #", "\"\"\" It verify the grades of the student @param: request", "obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students = set()", "Array to be converted to xlsx k -temporary array to", "to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc", "of the student with that rollno # s - designation", "def verify_grade(request): \"\"\" It verify the grades of the student", "in a curriculum. It checkes the authentication of the user", "of student from file hall_no - details of student from", "Exception as e: request_batch = \"\" request_branch = \"\" request_programme", "data - data of delete dictionary in post request t", "student is a convenor/coconvenor to be deleted # data -", "'curriculum': curriculum, 'faculty_list': faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\",", "formatting variable of title the workbook subtitle - formatting variable", "from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import", "- the student object of the student # \"\"\" e", "# # curriculum # # #################################### @login_required def curriculum(request): \"\"\"", "4 num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1", "return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['5','1'] } if request.method ==", "Exam time table to be deleted \"\"\" if user_check(request): return", "details which is selected by the academic admin. # \"\"\"", "HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES: # form", "= get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try: request_batch =", "# form = MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save()", "request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now", "else: context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context)", "page # @variables: # data - the id of the", "Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses,", "= \"\" request_programme = \"\" request_sem = \"\" #for checking", "pk, # } # s.delete() # e.delete() # u.delete() #", "context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list':", "return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method ==", "while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST:", "== \"POST\": # print(request.POST) # rollno=request.POST.get('roll') # print(rollno) # student", "- contains metadata about the requested page @variables: current_user -", "be displayed in the webpage \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "designation of the current user # acadadmin - deatils of", "\"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can upload the", "curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now =", "# data = { # 'rollno': pk, # } #", "# to add a new student senator # @param: #", "return JsonResponse(data) # else: # data = {} # return", "HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It adds", "ans - Formatted Array to be converted to xlsx k", "def add_curriculum(request): \"\"\" This function is used to add new", "Successfully\") def add_advanced_profile(request): # \"\"\" # It adds the advance", "to check if the student is available desig_id - mother's", "applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This function is", ") einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address,", "course-name from form.REQUEST course_id - course_id from database credits -", "if request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES)", "except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\"", "num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split()", "return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context) return", "= [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details", "AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades,", "of the student # data - tag whether to delete", "of) of the semester. @param: request - contains metadata about", "'assistant_flag' : assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag }", "month <= 12: return [1, 3, 5, 7] else: return", "event. prev_desc - Description for the previous event which is", "from the database for the previous Description. \"\"\" if user_check(request):", "if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for p", "Acadadmin final_user - final designation of request user \"\"\" try:", "if stu not in registered_students: unregistered_students.add(stu) data = [] m", "# hDes.designation = s # else: # hDes.designation = p", "[2, 4, 6, 8] else: course_list_2 = [1, 3, 5,", "the student @param: request - contains metadata about the requested", "data = request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return", "the academic admin. # \"\"\" if request.method == \"POST\": pass", "###################################################### # # ##########Student basic profile################## # @csrf_exempt def add_basic_profile(request):", "object to be deleted # t - the minute object", "'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'],", "{ 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def", "the student is available desig_id - mother's name of the", "@variables: batch - gets the batch course - gets the", "MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting,", "Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation')", "i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt", "academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all()", "0, category = category, hall_no = hall_no, specialization = specialization,", ":['3','1'] } if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch']", "- the student object of the new senator # data", ") new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request,", "return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # st =", "student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return", "meeting objects held in senator meetings minuteForm - the form", "= Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper()", "= Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request,", "- course-name from form.REQUEST course_id - course_id from database credits", "= Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable =", "address # cpi - student's cpi # hall - hall", "requested page # @variables: # current_user - details of the", "Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date", "hDes.save() # student = Student.objects.get(id=extraInfo) # data = { #", "def deleteConvenor(request, pk): # \"\"\" # to remove a convenor/coconvenor", "for obj in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status", "# to add a new student convenor/coconvenor # @param: #", "- details of student from file fathers_name - details of", "# current_user - details of the current user. # desig_id", "assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context':", "courses by the academic person. # course - Course details", "# print (temp) # print (current_user) # acadadmin = temp.working", "to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save()", "rollno # s - designation object of Convenor # p", "about the requested page @variables: current_user - father's name of", "Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id'", "batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title)", "for normal text sheet - xlsx sheet to be rendered", "page @variables: request_batch - Batch from form request_branch - Branch", "batch - gets the batch course - gets the course", "entries in a curriculum. It checkes the authentication of the", "calendar = \"\" this_sem_courses = \"\" next_sem_courses = \"\" courses", "next semester obj - All the registration details appended into", "hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum", "Description. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context=", "to_date[0].split('-') to_date = [int(i) for i in to_date] to_date =", "metadata about the requested page. @variables: profiles - gets the", "rollno of the student # batch - the current batch", "is used to set up the homepage of the application.", "= datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date = [int(i) for i", "examTtForm - the form required to add exam timetable exam_t", "\"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark", "sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch =", "to be added sem - semester of the student grade", "inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, )", "of the current user # acadadmin - deatils of the", "- contains metadata about the requested page. @variables: f1,f2,f3 -", "particualr student is holding the senator designation # student -", "\"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for", "= Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE", "to display it on the page. @param: request - contains", "\"\"\" This function is used to set up the homepage", "== \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return", "st = 'attachment; filename = ' + batch.name + batch.discipline.acronym", "the database # @param: # request - contains metadata about", "MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\")", "return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\",", "user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme = request.POST['programme']", "extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # # return JsonResponse(data)", "holdsDesignation object to store that the particualr student is #", "z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students: z =", "student's address # cpi - student's cpi # hall -", "ph, # 'batch': batch # } # print(data) # return", "= Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses =", "in the webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p", "that rollno # s - designation object of Convenor #", "Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models", "# s - the designation object that contains convenor #", "Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name = \"\" #", "'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" :", "Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all()", "'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else: context= {", "title - details of student from file dob - details", "thsi semester courses next_sem_courses - the data of next semester", "to float courses for the next sem and store data", "st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id =", "confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method", "pk): # \"\"\" # to remove a convenor/coconvenor from the", "current batch of the student # programme - the programme", "dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch =", "return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] # d", "JsonResponse(data) # else: # data = {} # return JsonResponse(data)", "chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins)", "entry to the academic calendar to be uploaded @param: request", "and must be acadadmin @param: request - contains metadata about", "0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else:", "csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request):", "return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4,", "render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to float courses", "event to the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align':", "which is selected by the academic admin. # \"\"\" if", "- to check the designation of the user. # user_details", "information like hall no, room no, # profile picture, about", "# desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation", "optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[]", "dep - temporary variables z - temporary variables for final", "new senate meeting minute object to the database. # @param:", "student is holding the senator designation # student - the", "if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot =", "import pisa from itertools import chain from django.contrib.auth.models import User", "= get_context(request) return render(request, \"ais/ais.html\", context) # #################################### # #", "desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar", "request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request,", "= json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return", "# data - the id of the minute object to", "credit details from forms and the append it to an", "'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type,", "} if request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\"", "# e - the extraInfo objects of the student #", "sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp =", "data.append(z) for i in registered_students: z = [] z.append(m) m", "context) @login_required def update_calendar(request): \"\"\" to update an entry to", "HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] # d =", "if request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES)", "- contains metadata about the requested page @variables: senates -", "the databases to display it on the page. @param: request", "c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\",", "of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\"))", "set minimum credit for a current semester that a student", "course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem", "# sem.save() # return HttpResponse(\"Worked\") def view_course(request): # if request.method", "= Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme = \"M.Tech\")", "- used to check the designation ID. # extraInfo -", "- contains metadata about the requested page. @variables: profiles -", "hod_flag = obj.hod_status account_flag = obj.account_status except Exception as e:", "entry to the academic calendar to be updated. @param: request", "\"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete() return HttpResponse(\"TimeTable", "= sem_for_generate_sheet() if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else:", "entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum =", "# if request.method == \"POST\": # data = request.POST['delete'] #", "st = 'attachment; filename = ' + course.code + '.xlsx'", "about the requested page # @variables: # name - the", "registration details appended into one data - Formated data for", "'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method == 'POST'", "name of the student # user_details - the rollno of", "request - contains metadata about the requested page @variables: request_batch", "choices - selected addtional courses by the academic person. #", "def float_course(request): \"\"\" to float courses for the next sem", "get faculty list from database @param: request - contains metadata", "else: # return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {})", "[] # for des in hDes: # if des.designation ==", "to add academic calender examTtForm - the form required to", "examTtForm = ExamTimetableForm() if request.method == 'POST' and request.FILES: examTtForm", "extraInfo objects that holds the designation as a senator students", "examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\",", "Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() #", "hDes = get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() #", "request.method == \"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete()", "= batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set() unregistered_students", "i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex", "context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet():", "\"\" request_branch = \"\" request_programme = \"\" if request_batch ==", "course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum':", "- tag whether to delete it or not # course", "= des.designation.name # des.delete() # data = { # 'id':", "student # batch - the current batch of the student", "# 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name #", "Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE", "obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id) for stu in", "\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) #", "from database courses - get courses from database courses_type -", "addMinute(request): # \"\"\" # to add a new senate meeting", "Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\"", "- the student object of the new convenor/coconvenor # data", "return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method == 'POST':", "credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code,", "faculty_list @login_required def float_course(request): \"\"\" to float courses for the", "the college attendance - all the attendance objects of the", "return context @login_required def homepage(request): \"\"\" This function is used", "io import BytesIO from xlsxwriter.workbook import Workbook from xhtml2pdf import", "course ofwhich the grade is added \"\"\" # if user_check(request):", "Courses, Batch, Semester, Programme, Discipline) from applications.academic_procedures.views import acad_proced_global_context from", "temporary variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "datetime month - current month \"\"\" now = datetime.datetime.now() month", "request.POST.get('cpi') # student.address = str(hall) + \" \" + str(room)", "== 'POST': programme = request.POST['programme'] now = datetime.datetime.now() year =", "sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num = 1 for i", "and store data in databsae. User must be logged in", "last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex,", "'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method == 'POST'", "- gets the course curr_key - gets the curriculum from", "data for context m - counter for Sl. No (in", "the list students that is a senator # hDes -", "# print(student.address) # if not student: # data = {}", "# course.acad_selection = True # course.save() # courses = Course.objects.all()", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(\"confirm", "gets basic gata from database to send to template @param:", "variable of subtitle the workbook normaltext - formatting variable for", "address - details of student from file department - details", "details from forms and the append it to an array.", "!= str(final_user)): return True else: return False def get_context(request): \"\"\"", "Formated data for context m - counter for Sl. No", "request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "# holding the convenor/coconvenor designation # student - the student", "= HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id = Semester.objects.get(curriculum =", "sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme,", "User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo = ExtraInfo.objects.create(", "= { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list,", "request_programme - Programme from form request_sem - Semester from form", "- batch form form curriculum - curriculum details form database", "'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag, 'hod_flag'", "phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme", "i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to", "= specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create(", ": courses, # 'course_type' : course_type, # 'curriculum' : curriculum,", "data = [] m = 1 for i in unregistered_students:", "from form request_programme - Programme from form request_sem - Semester", "course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context)", "the designation of the user. # user_details - to get", "request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return", "\"\" and request_branch == \"\" and request_programme==\"\": curriculum = None", "obj - All the registration details appended into one data", "return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == \"POST\":", "is added \"\"\" # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') #", "- grade to be added in the student course -", "\"POST\": # data = request.POST['delete'] # t = Meeting.objects.get(id=data) #", "the academic calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar =", "15, 'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size':", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar'", "metadata about the requested page. @variables: from_date - The starting", "##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\" #", "hDes = HoldsDesignation() # hDes.user = extraInfo.user # hDes.working =", "student.save() # s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother #", "file specialization - details of student from file hall_no -", "the Student class Convenor - the extraInfo objects that holds", "context= { 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) context=", "in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst =", "= Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all()", "e = get_object_or_404(ExtraInfo, id=pk) # user = get_object_or_404(User, username =", "3, 5, 7] else: return [2, 4, 6, 8] @login_required", "dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value", "a new senate meeting minute object to the database. #", "'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context) else:", "time year - getcurrent year batch - gets the batch", "whether to delete it or not # course - get", "request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem) == 0:", "render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function is", "Assistantship_status.objects.all() for obj in assis_stat: assistant_flag = obj.student_status hod_flag =", "Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] == '1': new_curriculum=[]", "final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch =", "the exam timtable of the ongoing semester. @param: request -", "student convenor/coconvenor # @param: # request - contains metadata about", "object of student currs - get curriculum details reg -", "object of the student # s - the student object", "curriculum details form database ins - Inster data in database", "user_details - to get the details of the required user.", "rollno - the rollno of the student required to check", "a,b,c,d,e = str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext)", "batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch =", "if request.method == 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo", "for final output b - temporary variables for final output", "in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2']", "c = get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk)", "form request_sem - Semester from form \"\"\" if user_check(request): return", "credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch", "render from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from", "# t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### # # ##########Student", "return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin can", "obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except Exception as", "# acadadmin - deatils of the acad admin # s", "user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= { 'academic_calendar' :calendar,", "examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "st - temporary variables for final output \"\"\" if user_check(request):", "- course_type from form.REQUEST ins - data is stored in", "temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print", "of the application. It checkes the authentication of the user", "about the requested page. # @variables: # sem_cred = Get", "objects exam_t - all the exam timetable objects timetable -", "+ course.code + '.xlsx' response['Content-Disposition'] = st return response @login_required", "to add attendance data to database # def curriculum(request): #", "one data - Formated data for context m - counter", "\"\"\" # to set minimum credit for a current semester", "- sheet no in excel file roll_no - details of", "fathers_name, mother_name = mothers_name, cpi = 0, category = category,", "def delete_basic_profile(request, pk): # \"\"\" # Deletes the student from", "\"\"\" # It adds the basic profile information like username,password,", "student required to check if the student is available #", "sem.credits = sem_cred[i+1] # sem.save() # return HttpResponse(\"Worked\") def view_course(request):", "= request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for i", "request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') #", "# 'course_type': course_type, # 'curriculum_course': curriculum_courses, # } # return", "HttpResponse('sucess') # else: # return HttpResponse('not uploaded') # return render(request,", "context= { 'tab_id' :['5','1'] } if request.method == 'POST': try:", "(str(p.course_id) == course): # print(p.course_id) # p.delete() # else: #", "cpi = 0, category = category, hall_no = hall_no, specialization", "# rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s", "JsonResponse(data)# ######################################################### # ''' # # view to add attendance", "student @param: request - contains metadata about the requested page", "acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This", "in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg)", ":\"2\" # } # return render(request,\"ais/ais.html\", context) # else: #", "a dean student - the students as a senator extra", "== \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc", "curriculum = None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum", "check the designation ID. # extraInfo - extraInfo object of", "Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp)", "# hDes.save() # student = Student.objects.get(id=extraInfo) # data = {", "meetings minuteForm - the form to add a senate meeting", "contains metadata about the requested page. @variables: examTtForm - data", "the all meeting objects held in senator meetings minuteForm -", "title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20)", "ph # db.save() # st.save() # data = { #", ":['3','1'] } if request.method == \"POST\": dele = Curriculum.objects.select_related().filter(curriculum_id=request.POST['id']) dele.delete()", "= ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co", "the particular student is a senator # \"\"\" pass #", "batch_id) for stu in students: if stu not in registered_students:", "range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if sex == 'F':", "'rollno': extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name # }", "sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1 for", "new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username =", "name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo,", "of the acad admin # s - the student object", "course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses", "= get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0:", "+ batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text,", "request.method == \"POST\": # st = request.POST['delete'] # arr =", "student object of the student # \"\"\" e = get_object_or_404(ExtraInfo,", "to be displayed in teh webpage # \"\"\" # current_user", "sex=str(sheet.cell(i,4).value) if sex == 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5)", "student # @param: # request - contains metadata about the", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\"", "if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception", "the append it to an array. # sem - Get", "the designation ID. # extraInfo - extraInfo object of the", "assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1':", "# if request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student", "contains co convenor # student - the student object with", "# else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def", "@login_required def generatexlsheet(request): \"\"\" to generate Course List of Registered", "- the holdDesignation object that stores the # information that", "data = { # 'name': name, # 'rollno': roll.id, #", "about the requested page # @variables: # current_user - the", "- The ending date for the academic caldendar event. desc", "object with the given pk # hDes - the holdDesignation", "= Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') # # ###################################################### #", "# s = Student.objects.get(id=stu) # s.father_name = \"\" # s.mother_name", "in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1']", "e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\"", "= Constants.COURSE_TYPE # context= { # 'courses': courses, # 'course_type':", "student object from the requested rollno # \"\"\" current_user =", "to be displayed in the webpage this_sem_course - tha data", "delete_basic_profile(request, pk): # \"\"\" # Deletes the student from the", "data to formatted array/variable output - io Bytes object to", "# student = Student.objects.get(id=extraInfo) # data = { # 'name':", "if request.method == \"POST\": name = request.POST.get('name') # roll =", "requested page @variables: programme - programme from form.REQUEST batch -", "the requested page # @variables: # name - the name", "student from file programme - details of student from file", "{} # return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): #", "post request t - Object of Exam time table to", "exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id'", "request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except", "context) def get_faculty_list(): \"\"\" to get faculty list from database", ":['5','1'] } if request.method == \"POST\": i=1 while True: if", "sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1", "advance profile information like hall no, room no, # profile", "pre-registration @param: request - contains metadata about the requested page", "course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"]", "# 'batch': batch # } # print(data) # return JsonResponse(data)", "data - data of the student to be displayed in", "add_convenor(request): # \"\"\" # to add a new student convenor/coconvenor", "# \"\"\" # to remove a convenor/coconvenor from the position", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if", "# i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" #", "'rollno': pk, # } # s.delete() # e.delete() # u.delete()", "} if request.method == 'POST': i=0 new_curr=[] while True: if", "sex - details of student from file title - details", "- all the departments in the college attendance - all", "# hDes - holdsDesignation object to store that the particualr", "= extraInfo.user # hDes.designation = s # hDes.save() # student", "# user_details - the rollno of the student required to", "to add exam timetable exam_t - all the exam timetable", "if \"semester_\"+str(i) in request.POST: try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)]", "the form required to add exam timetable Dean - the", "\"\"\" # to add a new student senator # @param:", "= sem_id) courses = [] for course_slot in course_slots: courses", "course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id = c,", "\"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('not registered') data.append(z) for i in registered_students: z", "registered_students = set() unregistered_students = set() for stu in obj:", "rollno=request.POST.get('roll') # print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) #", "convenor/coconvenor to be deleted # data - data of the", "Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s", "= True # course.save() # courses = Course.objects.all() # for", "new student object created in database desig - get designation", "metadata about the requested page. @variables: f1,f2,f3 - temporary varibles", "book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext =", "Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable,", "metadata about the requested page @variables: programme - programme from", "in registered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username)", "= desc get_calendar_details.from_date = from_date get_calendar_details.to_date = to_date get_calendar_details.save() except", "webpage # \"\"\" s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co", "= st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu): #", "= ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: # data", "for stu in students: if stu not in registered_students: unregistered_students.add(stu)", "HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course'])", "HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def", "requested page. @variables: f1,f2,f3 - temporary varibles faculty - details", "get hold_desig object of student currs - get curriculum details", "render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request):", "unregistered_students.add(stu) data = [] m = 1 for i in", "data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True}) title = book.add_format({'bold':", "# ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\"", "registered_courses: k = [] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort()", "request.method == \"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST:", "ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db =", "# @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes the", "= 0, category = category, hall_no = hall_no, specialization =", "requested page. @variables: request_batch - Batch from form request_branch -", "= render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return render(request, \"ais/ais.html\", context) return", "month - current month \"\"\" now = datetime.datetime.now() month =", "# student - the student object with the given pk", "HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return", "# acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses", "exam timetable. @param: request - contains metadata about the requested", "sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id", "user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": #", "= request.POST['programme'] except Exception as e: request_batch = \"\" request_branch", "Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save() # courses =", "- deatils of the acad admin # father - father's", "student to be displayed in the webpage # \"\"\" s", "Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user", "- get curriculum details reg - create registeration object in", "if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) # for i", "get_object_or_404(Student, id=e) # data = { # 'rollno': pk, #", "10): # sem = \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i", "# to delete an existing senate meeting minute object from", "(in formated data) z - temporary array to add data", "current_user - get user from request user_details - extract details", "# st.phone_no = ph # db.save() # st.save() # data", "form to add academic calender examTtForm - the form required", "# 'rollno': roll.id, # 'programme': programme, # 'phoneno': ph, #", "# course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t", "sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st", "# if request.method == \"POST\": # print(\"confirm hone wala hai\")", "course_id=course_id, credits=credits, optional=optional, course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr)", "datas to be displayed in the webpage this_sem_course - tha", "to template @param: request - contains metadata about the requested", "\"\"\" # to delete the advance information of the student", "Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working", "metadata about the requested page @variables: dele - data being", "the designation of the current user # acadadmin - deatils", "acad-admin can delete the outdated timetable from the server. @param:", "data from database ans - Formatted Array to be converted", "# desig_id - used to check the designation ID. #", "from file sex - details of student from file title", "= Designation.objects.get(name='Co Convenor') # if request.method == 'POST': # rollno", "of the student to become the convenor/coconvenor # extraInfo -", "user # sem - current semester of the student #", "context= { 'tab_id' :['5','1'] } if request.method == \"POST\": i=1", "stores the # information that the particular student is a", "Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester,", "request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem']", "'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration :", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context= {", "department=department, ) sem=1 stud_data = Student.objects.create( id=einfo, programme = programme_name,", "semester grade sheet @variables: now - current datetime month -", "= { # 'id': pk, # 'designation': designation, # }", "'name': extraInfo.user.username, # 'rollno': extraInfo.id, # 'programme': student.programme, # 'branch':", "= str(i[0]),str(i[1]),str(i[2]),str(i[3]),str(i[4]) temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1", "delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable from the", "preresgistration report after pre-registration @param: request - contains metadata about", "temp.working k = str(user_details).split() final_user = k[2] except Exception as", "course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\"", "e - the extraInfo objects of the student # user", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate Attendance Sheet", "request.method == \"POST\": pass # print(request.POST) # choices = request.POST.getlist('choice')", "- Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context=", "= programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return", "address subject - subject of which the grade has to", "= branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) #", "not in registered_students: unregistered_students.add(stu) data = [] m = 1", "django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import", "request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as", "from file email - details of student from file sex", "data faculty_list - list of faculty \"\"\" try: f1 =", "context m - counter for Sl. No (in formated data)", "to update an entry to the academic calendar to be", "the excel file having data excel - excel file sheet", "'tab_id' :['5','1'] } if request.method == \"POST\": i=1 while True:", "to be hidden in the webpage # \"\"\" # s", "'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) #", "to generate preresgistration report after pre-registration @param: request - contains", "# return render(request, \"ais/ais.html\", context) # else: # return render(request,", "of the required user. # desig_id - used to check", "the database.User must be logged in and must be acadadmin", "data of the student to be hidden in the webpage", "of the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) #", "sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch =", "'2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch,", "HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin = temp.working k = str(user_details).split() final_user", "of the new senator # data - data of the", "for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] a,b,c,d,e", "database and the update it. # \"\"\" if request.method==\"POST\": sem_cred", ":['3','2'] } return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother # s.hall_no =", "= Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','2']", "{ # 'grades': grades, # 'tab_id' :\"2\" # } #", "@param: request - contains metadata about the requested page @variables:", "the id of the minute object to be deleted #", "academic calendar to be updated. @param: request - contains metadata", "for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[] for c", "# data = {} # return JsonResponse(data) # else: #", "of student from file first_name - details of student from", "function is used to add new curriculum in database It", "- checking the designation of the current user # acadadmin", "HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/')", "that contains convenor # c - the designation object that", "new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem,", "is available desig_id - mother's name of the student acadadmin", "'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else: return render(request,", "s.save() # else: # return HttpResponse(\"Data Does Not Exist\") #", "# user_details - the details of the current user #", "- data of the student to be displayed in the", "- details of student from file user - new user", "current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id", "next_sem_courses = Curriculum.objects.all().filter(sem__in=course_list).filter(floated=True) # courses = Course.objects.all() # course_type =", "- Programme from form request_sem - Semester from form \"\"\"", "- excel file sheet - sheet no in excel file", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data =", "# return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST)", "that holds the designation as a convenor CoConvenor - the", "of new upcoming students in the database.User must be logged", "from current time now - get current time year -", "enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst)", "Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin", "convenor or coconvenor # hDes - holdsDesignation object to store", "= AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list", "exam timetable Dean - the extraInfo objects that holds the", "{ 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type':", "# grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades,", "courses: # if i.course_id not in choices: # i.acad_selection =", "request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course =", "return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/')", "the logged in user # user_details - the details of", "JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request,", "'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function is used", "HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST': try:", "file mothers_name - details of student from file category -", "c in courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data )", "def confirm_grades(request): # if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if", "temp = str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0)", "the required user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username)", "# \"\"\" # to delete the advance information of the", "as a convenor CoConvenor - the extraInfo objects that holds", "student from file title - details of student from file", "delete dictionary in post request t - Object of Exam", "= \"\" exam_t = \"\" pass context = { 'acadTtForm':", "= Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #", "import xlrd import logging from io import BytesIO from xlsxwriter.workbook", "= request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all() course_type =", "room no, # profile picture, about me etc of a", "semester. @param: request - contains metadata about the requested page.", "- new user created in database einfo - new extrainfo", "i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id,", "try: programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if", "subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'})", "hDes.save() # data = { # 'name': extraInfo.user.username, # 'rollno_convenor':", "request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj = course_registration.objects.all().filter(course_id =", "'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name)", "AcademicTimetableForm() if request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST,", "to write to xlsx file book - workbook of xlsx", "return HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" #", "to_date = to_date[0].split('-') to_date = [int(i) for i in to_date]", "minimum credits from the database and the update it. #", "page # pk - the primary key of that particular", "the user. # user_details - to get the details of", "- mother's name of the student acadadmin - student's address", "of subtitle the workbook normaltext - formatting variable for normal", "for any particular curriculum if request_batch == \"\" and request_branch", "desig_id - check for designation acadadmin - designation for Acadadmin", "batch # } # print(data) # return JsonResponse(data) # else:", "# ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists(): # db", "excel file having data excel - excel file sheet -", "float_course_submit(request): \"\"\" to float courses for the next sem and", "# else: # data = {} # return JsonResponse(data) #", "} # return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute##################", "\"\" course_type = \"\" timetable = \"\" exam_t = \"\"", "exam timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable", "e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return render(request,", "'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm()", "== 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0]", "@login_required def generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration", "@login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated exam", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\"", "current_user - details of the current user. # desig_id -", "= request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date =", "as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\"", "sem - Get the object for the minimum credits from", "id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) # designation =", "desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, )", "datetime.datetime.now() year = int(now.year) if sem[0] == 2: sem =", "ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else:", "which the grade has to be added sem - semester", "return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def", "str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type", "except Exception as e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\"", "ending date for the academic caldendar event. desc - Description", "= batch # db.programme = programme # st.phone_no = ph", "data - Formated data for context m - counter for", "for c,i in enumerate(request.POST.getlist(str(i)+'_fac')): inst = get_object_or_404(User, username = i)", "\"\" # s.hall_no = 1 # s.room_no = \"\" #", "c: # designation = des.designation.name # des.delete() # data =", "z.append('not registered') data.append(z) for i in registered_students: z = []", "# curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem =", "return render(request, \"ais/ais.html\", context) # #################################### # # curriculum #", "= obj.account_status except Exception as e: examTtForm = \"\" acadTtForm", "student from file fathers_name - details of student from file", "return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] } return", "request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception as", "context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1']", "Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm", "} courses = Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request)", "variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try:", "delete data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\"", "student # data - tag whether to delete it or", "students - all the objects in the Student class Convenor", "programme=request.POST['AddProgramme'] batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i)", "data is stored in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "sem=sem) # for p in s: # if (str(p.course_id) ==", "designation as a dean student - the students as a", "get course types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "academic calender examTtForm - the form required to add exam", "timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent = Student.objects.filter(programme =", "HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except", "if the student is available desig_id - mother's name of", "# \"\"\" pass # if request.POST: # s = get_object_or_404(Designation,", "# 'courses' : courses, # 'course_type' : course_type, # 'curriculum'", "render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function is", "course types from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context", "the student # s - the student object of the", "particualr student is # holding the convenor/coconvenor designation # student", "# 'tab_id' :['3','1'] # } courses = Course.objects.all() course_type =", "request.POST.get('room') # cpi = request.POST.get('cpi') # student.address = str(hall) +", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] }", "adds the advance profile information like hall no, room no,", "course_type - course_type from form.REQUEST ins - data is stored", "metadata about the requested page # pk - the primary", "CoConvenor - the extraInfo objects that holds the designation as", "the workbook normaltext - formatting variable for normal text sheet", "= request.POST.get('address') # hall = request.POST.get('hall') # room = request.POST.get('room')", "(Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from", "c = object to save new event to the academic", "@login_required def edit_curriculum(request): \"\"\" This function is used to edit", "and the update it. # \"\"\" if request.method==\"POST\": sem_cred =", "hDes.designation.name, # } # return JsonResponse(data) # else: # data", "grade has to be added sem - semester of the", "added sem - semester of the student grade - grade", "be added in the student course - course ofwhich the", "final_user = k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass", "#################################################### # # ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request):", "extraInfo object of the student with that rollno # s", "from the requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username)", "- Semester from form curriculum - Get data about curriculum", "the student grade - grade to be added in the", "student is available # desig_id - mother 's name of", "the server. @param: request - contains metadata about the requested", "dictionary in post request t - Object of time table", "output c - temporary variables for final output st -", "to delete the advance information of the student # @param:", "request - contains metadata about the requested page @variables: senates", "int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme=", "Discipline) from applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required", "== \"POST\": # print(\"confirm hone wala hai\") # print(request.POST) return", "batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj =", "details of student from file first_name - details of student", "k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book = Workbook(output,{'in_memory':True})", "# i.acad_selection = False # i.save() # return HttpResponseRedirect('/academic-procedures/') def", "for the next sem and store data in databsae. User", "# k = str(user_details).split() # print(k) # final_user = k[2]", "used to add new curriculum in database It checkes the", "# if des.designation == s or des.designation == c: #", "# s - the student object of the student #", "examTtForm = \"\" acadTtForm = \"\" calendar = \"\" this_sem_courses", "= request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] request_sem =", "assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'],", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete']", "Constants.COURSE_TYPE # context= { # 'courses': courses, # 'course_type': course_type,", "\"\"\" This function is used to check the type of", "the ongoing semester. @param: request - contains metadata about the", "curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) if request.POST['option'] ==", "programme_name, discipline__acronym = dept, year = batch_year).first() user = User.objects.create_user(", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST'", "sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type", "senate meeting minute object from the database. # @param: #", "request - contains metadata about the requested page @variables: dele", "'id': pk, # 'designation': designation, # } # return JsonResponse(data)#", "with that rollno # s - designation object of senator", "True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if", "# ''' def delete_advanced_profile(request): # \"\"\" # to delete the", "# sem - current semester of the student # data", "requested page. # @variables: # sem_cred = Get credit details", "acadadmin - student's address # final_user - details of the", "database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] }", "@login_required def homepage(request): \"\"\" This function is used to set", "of the student # @param: # request - contains metadata", "acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar =", "acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all() # this_sem_courses =", "of student from file sex - details of student from", "from file title - details of student from file dob", "'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15, 'align': 'center',", "pgstudent = Student.objects.filter(programme = \"M.Tech\") | Student.objects.filter(programme = \"PhD\") assistant_list", "# ##########covenors and coconvenors################## # @csrf_exempt def add_convenor(request): # \"\"\"", "Course.objects.all() # course_type = Constants.COURSE_TYPE # context= { # 'courses':", "'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration : \"+ batch.name", "Grades.objects.filter(student_id=id, sem=sem) # for p in s: # if (str(p.course_id)", "desig_id - to check the designation of the user. #", "year = int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1]", "print(rollno) # student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not", "convenor/coconvenor designation # student - the student object of the", "of student from file title - details of student from", "as a senator extra - all the extraInfor objects exam_t", "webpage this_sem_course - tha data of thsi semester courses next_sem_courses", "for i in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-')", "the student stays # room no - hostel room no", "\"\"\" acad-admin can upload the time table(any type of) of", "str(\" \") + batch.discipline.acronym + str(\" \") + str(batch.year)) sheet.set_default_row(25)", "= datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" pass", "cpi - student's cpi # hall - hall no of", "= \"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses =", "- subject of which the grade has to be added", "to be uploaded @param: request - contains metadata about the", "= st return response @login_required def generate_preregistration_report(request): \"\"\" to generate", "# data = request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete()", "= batch_id) for stu in students: if stu not in", "Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id'", "course.save() # courses = Course.objects.all() # for i in courses:", "ExamTimetableForm, MinuteForm from .models import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants,", "details of new upcoming students in the database.User must be", "designation object that contains co convenor # student - the", "import Workbook from xhtml2pdf import pisa from itertools import chain", "# return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request): # if user_check(request):", "True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark =", "'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center',", "- to get the details of the required user. #", "# return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data = request.POST['delete'] #", "and the append it to an array. # sem -", "user. # user_details - to get the details of the", "as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context) return", "academic calendar event. prev_desc - Description for the previous event", "dob - details of student from file fathers_name - details", "student # user - the User object of the student", "student to be hidden in the webpage # \"\"\" #", "attendance objects of the students context - the datas to", "# else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def deleteSenator(request, pk):", "acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\", context)", "s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # result", "the student object from the requested rollno # \"\"\" current_user", "@variables: from_date - The starting date for the academic calendar", "dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value)", "delete the advance information of the student # @param: #", "holds_desig - get hold_desig object of student currs - get", "+ str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle)", "= request.POST['branch'] request_programme = request.POST['programme'] request_sem = request.POST['sem'] except Exception", "- the designation object that contains co convenor # student", "batch from form.REQUEST branch - branch from form.REQUEST sem -", "# st.save() # data = { # 'name': name, #", "[] k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO()", "to xlsx k -temporary array to add data to formatted", "} return render(request, \"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required", "next semester courses courses - all the courses in curriculum", "exam timetable objects timetable - all the academic timetable objects", "final output st - temporary variables for final output \"\"\"", "time table(any type of) of the semester. @param: request -", "of student from file address - details of student from", "details of student from file batch - details of student", "# } # print(data) # return JsonResponse(data) # else: #", "batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins)", "Convenor') # result = request.POST.get('designation') # hDes = HoldsDesignation() #", "stud_data = Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id =", "metadata about the requested page. @variables: request_batch - Batch from", "request.POST['option'] == '1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme,", "new curriculum in database It checkes the authentication of the", "contains metadata about the requested page. @variables: request_batch - Batch", "for Sl. No (in formated data) z - temporary array", "hDes - the holdDesignation object that stores the # information", "t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add", "- Inster data in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "request.method == \"POST\": try: from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date')", "that particular student field # @variables: # s - the", "= str(i[3]).split() sheet.write_string('B'+str(k),b,normaltext) sheet.write_string('C'+str(k),c,normaltext) sheet.write_string('D'+str(k),d,normaltext) sheet.write_string('E'+str(k),e,normaltext) k+=1 book.close() output.seek(0) response", "s - the student object of the student # \"\"\"", "22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size':", "response['Content-Disposition'] = st return response @login_required def generate_preregistration_report(request): \"\"\" to", "particular curriculum if request_batch == \"\" and request_branch == \"\"", "the designation object that contains co convenor # student -", "coconvenor # hDes - holdsDesignation object to store that the", "= book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) sheet", "designation object of Convenor # p - designation object of", "department - details of student from file specialization - details", "- data of delete dictionary in post request timetable -", "if form.is_valid(): # form.save() # return HttpResponse('sucess') # else: #", "to check the designation of the user. # user_details -", "in curriculum course_type - list the type of courses \"\"\"", "# extraInfo - extraInfo object of the student with that", "form to add a senate meeting minutes acadTtForm - the", "from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\", context)", "#Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester", "in the Student class Convenor - the extraInfo objects that", "response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename =", "the user and also fetches the available data from the", "##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): # \"\"\" #", "# branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch", "@variables: # s - the designation object that contains senator", "if user_check(request): # return HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\":", "sheet.set_column('B:B',20) sheet.set_column('C:C',50) sheet.set_column('D:D',15) sheet.set_column('E:E',15) k = 4 num = 1", "k = str(user_details).split() final_user = k[2] except Exception as e:", "= book.add_format({'bold': True, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'}) normaltext", "= \"\" request_branch = \"\" request_programme = \"\" if request_batch", "== \"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST: if", "'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = (\"Pre-registeration", "HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print (current_user) #", "acadadmin - student's address subject - subject of which the", "sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value)", "sem_cred.append(0) # for i in range(1, 10): # sem =", "this_sem_course - tha data of thsi semester courses next_sem_courses -", "all the academic timetable objects calendar - all the academic", "the grade is added \"\"\" # if user_check(request): # return", "gets the batch from form sem - stores the next", "optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\"", "= Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses = Course.objects.all()", "coconvenor meetings - the all meeting objects held in senator", "the extraInfo objects that holds the designation as a senator", "the requested page @variables: dele - data being deleted from", "page # @variables: # current_user - details of the current", "optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\"", "Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm =", "It checkes the authentication of the user and also fetches", "k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin)", "courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses,", "database desig - get designation object of student holds_desig -", "@variables: acadTtForm - the form to add academic calender examTtForm", "- Object of Exam time table to be deleted \"\"\"", "'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign':", "the designation object that contains senator # student - the", "\"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This function is used", "request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/') #", "formatting variable of subtitle the workbook normaltext - formatting variable", "# roll - the rollno of the student # batch", "'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if examTtForm.is_valid(): examTtForm.save()", "student stays # room no - hostel room no #", "request - contains metadata about the requested page # @variables:", "# sem - Get the object for the minimum credits", "request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch = year-1", "datetime import json import os import xlrd import logging from", "# s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user", "return JsonResponse(data) # else: # return HttpResponseRedirect('/aims/') # @csrf_exempt def", "# @variables: # current_user - details of the current user.", "= Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum,", "of a student # @param: # request - contains metadata", "# hall = request.POST.get('hall') # room = request.POST.get('room') # cpi", "# if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) #", "the user. @param: request - contains metadata about the requested", "timetable objects calendar - all the academic calender objects department", "student from file last_name - details of student from file", "object that contains co convenor # student - the student", "store that the particualr student is holding the senator designation", "of the student to be displayed in teh webpage #", "designation as a coconvenor meetings - the all meeting objects", "the workbook subtitle - formatting variable of subtitle the workbook", "dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response", "created in database desig - get designation object of student", "def delete_timetable(request): \"\"\" acad-admin can delete the outdated timetable from", "Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return render(request, \"ais/ais.html\",", "has to be added sem - semester of the student", ":['3','2'] } return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1']", "details of student from file email - details of student", "batch - details of student from file user - new", "details reg - create registeration object in registeration table \"\"\"", "that contains senator # student - the list students that", "branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE", "add = request.POST.get('address') # hall = request.POST.get('hall') # room =", "the student # batch - the current batch of the", "branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum(", "all the attendance objects of the students context - the", "object that stores the # information that the particular student", "user. # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details", "# programme - the programme the student is enrolled in", "User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import", "page # @variables: # rollno - rollno of the student", "database desig_id - check for designation acadadmin - designation for", "z - temporary array to add data to variable data", "= \"\" # s.hall_no = 1 # s.room_no = \"\"", "sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st", "current date from system year - current year batch -", "the designation as a senator students - all the objects", "# pk - the primary key of the student's record", "else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem)", "# \"\"\" if request.method==\"POST\": sem_cred = [] # sem_cred.append(0) #", "# to remove a senator from the position # @param:", "= len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj in", "'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'],", "senator # hDes - holdsDesignation object to store that the", "the student with that rollno # s - designation object", "the course details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username)", ") new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme =", "@csrf_exempt def delete_basic_profile(request, pk): # \"\"\" # Deletes the student", "gets the curriculum from database obj - get stdents data", "used to set up the homepage of the application. It", "to decide curriculum for new batch. It checkes the authentication", "to the academic calendar to be uploaded @param: request -", "if request.method == 'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read())", "= category, hall_no = hall_no, specialization = specialization, curr_semester_no=sem, )", "normaltext = book.add_format({'bold': False, 'font_size': 15, 'align': 'center', 'valign': 'vcenter'})", "= [] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name)", "roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch =", "calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent,", "the student object of the new senator # data -", "= ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp", "= \"\" request_branch = \"\" request_programme = \"\" request_sem =", "st = request.POST['delete'] # arr = st.split(\"-\") # stu =", "in post request timetable - all timetable from database exam_t", "particular student is a convenor/coconvenor to be deleted # data", "examTtForm - data of delete dictionary in post request timetable", "= str(user_details).split() final_user = k[2] except Exception as e: acadadmin=\"\"", "from file programme - details of student from file batch", "context= { 'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required", "12: return [1, 3, 5, 7] else: return [2, 4,", "details of faculty of data faculty_list - list of faculty", "student grade - grade to be added in the student", "temp = str(i[3]).split() dep = str(temp[len(temp)-1]) sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1", "\"\"\" # to add a new senate meeting minute object", "Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the outdated", "in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag =", "- details of student from file email - details of", "render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def senator(request):", "of that particular student field # @variables: # s -", "email - details of student from file sex - details", "context= { # 'courses': courses, # 'course_type': course_type, # 'curriculum_course':", "else: # return render(request, \"ais/ais.html\") return render(request, \"ais/ais.html\") def delete_grade(request):", "of the ongoing semester. @param: request - contains metadata about", "# db.batch = batch # db.programme = programme # st.phone_no", "- the extraInfo objects of the student # user -", "- temporary variables for final output c - temporary variables", "# hDes.save() # data = { # 'name': extraInfo.user.username, #", "the extraInfor objects exam_t - all the exam timetable objects", "current_user - gets the data of current user. # user_details", "acadadmin @param: request - contains metadata about the requested page.", "the given pk # hDes - the holdDesignation object that", "formatting variable for normal text sheet - xlsx sheet to", "num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c", "= Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) # context={", "add data to variable data k -temporary array to add", "request.POST.get('address') # hall = request.POST.get('hall') # room = request.POST.get('room') #", "extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes =", "requested page @variables: current_user - father's name of the student", "if request_batch == \"\" and request_branch == \"\" and request_programme==\"\":", "# if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll') #", "programme=i.programme, batch=i.batch+1, branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, )", "= Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description = desc get_calendar_details.from_date = from_date get_calendar_details.to_date =", "return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method == 'POST':", "= \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty", "- tha data of thsi semester courses next_sem_courses - the", "# context={ # 'courses' : courses, # 'course_type' : course_type,", "as e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return", "array. # sem - Get the object for the minimum", "'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable, 'academic_calendar': calendar,", "= Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses': courses, 'course_type':", "== 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"]", "variables for final output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if", "= \"\" request_programme = \"\" if request_batch == \"\" and", "user # desig_id - checking the designation of the current", "# 'programme': student.programme, # 'branch': extraInfo.department.name # } # return", "= sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch", "hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# ####################################################", "user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') #", "see curriculum and edit entries in a curriculum. It checkes", "category - details of student from file phone_no - details", "# hDes.working = extraInfo.user # if result == \"Convenor\": #", "to be deleted \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method", "i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits", "set() unregistered_students = set() for stu in obj: registered_students.add(stu.student_id) students", "entry in database It checkes the authentication of the user", "the academic calender objects context - the datas to be", "'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam': exam_t, 'timetable': timetable,", "\"POST\": # st = request.POST['delete'] # arr = st.split(\"-\") #", "to send to template @param: request - contains metadata about", "Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) # print", "- semester from form.REQUEST course_code - course_code from form.REQUEST course_name", "metadata about the requested page @variables: sem - get current", "reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else:", "student from file batch - details of student from file", "if request.method == \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data)", "- temporary variables for final output b - temporary variables", "the requested page @variables: sem - get current semester from", "== '2': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1,", "except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses =", "store data in databsae. User must be logged in and", "== \"\" and request_branch == \"\" and request_programme==\"\" and request_sem==\"\":", "return [2, 4, 6, 8] @login_required def generatexlsheet(request): \"\"\" to", "curr_key - gets the curriculum from database obj - get", "title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value)", "= Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm", "= d[0] # course = d[2] # sem = int(d[3])", "authentication of the user and also fetches the available data", "from form.REQUEST now - current date from system year -", "request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll", "the current user # acadadmin - deatils of the acad", "from applications.programme_curriculum.models import (CourseSlot, Course as Courses, Batch, Semester, Programme,", "- get courses from database courses_type - get course types", "and request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum =", "to add data to formatted array/variable output - io Bytes", "designation for Acadadmin final_user - final designation of request user", "request_batch - Batch from form request_branch - Branch from form", "about the requested page @variables: acadTtForm - the form to", "# profile picture, about me etc of a student #", "= k[2] except Exception as e: acadadmin=\"\" final_user=\"\" pass if", "the student is available # desig_id - mother 's name", "= {} # return JsonResponse(data) # else: # father =", "student acadadmin - student's address subject - subject of which", "course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch,", "= c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request,", "# s.father_name=father # s.mother_name=mother # s.hall_no = hall # s.room_no", "\"POST\": data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable", "The starting date for the academic calendar event. to_date -", "def add_advanced_profile(request): # \"\"\" # It adds the advance profile", "the requested page @variables: current_user - get user from request", "== \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem']", "HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','1'] } if request.method == \"POST\": dele", "+= 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output =", "timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context()", "name = str(b)+\" \"+str(c) temp = str(i[3]).split() dep = str(temp[len(temp)-1])", "student from file sex - details of student from file", "== '1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1,", "course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST: optional=True else:", "= Timetable.objects.all() exam_t = Exam_timetable.objects.all() context= { 'exam': exam_t, 'timetable':", "branch=i.branch, sem=i.sem, course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum)", "# \"\"\" # to add a new student senator #", "user. @param: request - contains metadata about the requested page", "sheet - sheet no in excel file roll_no - details", "Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id =", "Deleted Successfully\") def add_advanced_profile(request): # \"\"\" # It adds the", "requested page @variables: programme - programme from form.REQUEST now -", "HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can delete the", "in database einfo - new extrainfo object created in database", "timetable. @param: request - contains metadata about the requested page.", "student # roll - the rollno of the student #", "from the database. # @param: # request - contains metadata", "- formatting variable of title the workbook subtitle - formatting", "= course) except Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\"", "- details of student from file programme - details of", "\" + str(room) # student.save() # s = Student.objects.get(id=student) #", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\"", "'POST' and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i", "course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i in obj:", "registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id'", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem", "# student - the student object of the new convenor/coconvenor", "convenor/coconvenor # @param: # request - contains metadata about the", "HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from django.template.loader", "i in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\"", "- gets the batch course - gets the course curr_key", "information that the particular student is a senator # \"\"\"", "# } # return JsonResponse(data) # else: # data =", "mother - mother's name of the student # add -", "= request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date =", "- contains metadata about the requested page. @variables: data -", "on the page. @param: request - contains metadata about the", "to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return", "metadata about the requested page @variables: current_user - get user", "'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch))))", "from id to be deleted # \"\"\" # if request.method", "=True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval", "add_new_profile (request): \"\"\" To add details of new upcoming students", "= extraInfo.user # hDes.working = extraInfo.user # hDes.designation = s", "file book - workbook of xlsx file title - formatting", "name of the student acadadmin - student's address subject -", "= \"\" timetable = \"\" exam_t = \"\" pass context", "get courses from database courses_type - get course types from", "= Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context= { 'curriculumm' :curriculum,", "# else: # return HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and", "obj.hod_status account_flag = obj.account_status except Exception as e: examTtForm =", "e: acadadmin=\"\" final_user=\"\" pass if (str(acadadmin) != str(final_user)): return True", "# sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): # sem", "Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme = programme) context=", "new student convenor/coconvenor # @param: # request - contains metadata", "for des in hDes: # if des.designation == s or", "Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all()", "str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': #", "be updated. get_calendar_details = Get the object of the calendar", "get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper", "itertools import chain from django.contrib.auth.models import User from django.http import", "requested page. @variables: examTtForm - data of delete dictionary in", "# 'curriculum' : curriculum, # 'tab_id' :['3','1'] # } courses", "of the current user # desig_id - checking the designation", "by the academic person. # course - Course details which", "def addMinute(request): # \"\"\" # to add a new senate", "sem_cred = [] # sem_cred.append(0) # for i in range(1,", "to be rendered titletext - formatting variable of title text", "timetable Dean - the extraInfo objects that holds the designation", "\"POST\": name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme", "obj - get stdents data from database ans - Formatted", "hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no", "senator from the position # @param: # request - contains", "to add new curriculum in database It checkes the authentication", "to be deleted # t - the minute object received", "# c - the designation object that contains co convenor", "'tab_id' :['3','2'] } if request.method == 'POST': i=0 new_curr=[] while", "- designation object of senator # hDes - holdsDesignation object", "des.delete() # data = { # 'id': pk, # 'designation':", "- current semester of the student # data - tag", "student is available desig_id - mother's name of the student", "updated. get_calendar_details = Get the object of the calendar instance", "email=email, ) einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob,", "of student currs - get curriculum details reg - create", "and edit entries in a curriculum. It checkes the authentication", "contains metadata about the requested page # @variables: # name", "the rollno of the student required to check if the", "of student from file email - details of student from", ": assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'],", "the requested page @variables: current_user - father's name of the", "# hDes - the holdDesignation object that stores the #", "deleteSenator(request, pk): # \"\"\" # to remove a senator from", "designation = [] # for des in hDes: # if", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request):", "output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename", "= request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme'] except Exception", "= get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student, id=e)", "einfo = ExtraInfo.objects.create( id=roll_no, user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no,", "i in unregistered_students: z = [] z.append(m) m += 1", "gets the data of current user. # user_details - gets", "will become # convenor or coconvenor # hDes - holdsDesignation", "# # ##########Senate meeting Minute################## # @csrf_exempt def addMinute(request): #", "num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c", "object to store that the particualr student is holding the", "contains metadata about the requested page @variables: dele - data", "= get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user) #", "curriculum, # 'tab_id' :['3','1'] # } courses = Course.objects.all() course_type", "add_curriculum(request): \"\"\" This function is used to add new curriculum", "in database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method ==", "student from file user - new user created in database", "pass if (str(acadadmin) != str(final_user)): return True else: return False", "- details of student from file last_name - details of", "from form request_branch - Branch from form request_programme - Programme", "registeration object in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details", "def add_timetable(request): \"\"\" acad-admin can upload the time table(any type", "courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t", "if i.course_id not in choices: # i.acad_selection = False #", "course - Course details which is selected by the academic", "can delete the outdated exam timetable. @param: request - contains", "student object of the new senator # data - data", "current_user = get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper", ": assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists':", "in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e:", "context) # else: # return HttpResponseRedirect('/aims/') return HttpResponseRedirect('/aims/') def confirm_grades(request):", "- father's name of the student # rollno - the", "- credits from form.REQUEST optional - optional from form.REQUEST course_type", "student = ExtraInfo.objects.get(id=rollno) # print(student.address) # if not student: #", "number of the student # \"\"\" if request.method == \"POST\":", "return HttpResponse(\"Worked\") def view_course(request): # if request.method == \"POST\": #", "# p - designation object of Co Convenor # result", "the data of next semester courses courses - all the", "- student's address # final_user - details of the user", "= False # i.save() # return HttpResponseRedirect('/academic-procedures/') def min_cred(request): #", "= datetime.datetime.now() year = int(now.year) batch = year-1 curriculum =", "previous event which is to be updated. get_calendar_details = Get", "is used to add new curriculum in database It checkes", "details of student from file phone_no - details of student", "generate Course List of Registered Students @param: request - contains", "st.split(\"-\") # stu = arr[0] # if Student.objects.get(id=stu): # s", "# print (current_user) # acadadmin = temp.working # k =", "user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": sem = request.POST.get('semester_no')", "# db = Student() # st = ExtraInfo.objects.get(id=roll.id) # db.name", "# add = request.POST.get('address') # hall = request.POST.get('hall') # room", "context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2']", "s.mother_name=mother # s.hall_no = hall # s.room_no = room #", "dept, year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name,", "page. @variables: acadTtForm - data of delete dictionary in post", "- contains metadata about the requested page # pk -", "@login_required def float_course_submit(request): \"\"\" to float courses for the next", "programme = request.POST.get('programme') # batch = request.POST.get('batch') # ph =", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context = get_context(request) context['tab_id'][0]='6' if request.method", "student is # holding the convenor/coconvenor designation # student -", "django.shortcuts import get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf", "k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st =", "about the requested page. @variables: request_batch - Batch from form", "decide curriculum for new batch. It checkes the authentication of", "now = datetime.datetime.now() month = int(now.month) if month >= 7", "HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method == 'POST'", "Students @param: request - contains metadata about the requested page", "the data that contains where the student will become #", "'align': 'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15,", "server. @param: request - contains metadata about the requested page.", "particular student is a senator # \"\"\" pass # if", "the type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list", "be displayed in teh webpage # \"\"\" # current_user =", "# s - the student object from the requested rollno", "acadadmin - designation for Acadadmin final_user - final designation of", "'attachment; filename = ' + course.code + '.xlsx' response['Content-Disposition'] =", "= Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\"", "= request.POST.get('room') # cpi = request.POST.get('cpi') # student.address = str(hall)", "sheet.write_string('B'+str(k),z,normaltext) sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type =", "the student to be displayed in the webpage # \"\"\"", "(request): \"\"\" To add details of new upcoming students in", "to delete it or not # course - get the", "i.student_id.batch_id.year == int(batch): registered_courses.append(i) ans = [] for i in", "from file batch - details of student from file user", "int(now.year) if sem[0] == 2: sem = sem[year-int(request_batch)-1] else: sem", "of student from file last_name - details of student from", "# s.hall_no = 1 # s.room_no = \"\" # s.save()", "semester_id__semester_no=sem) registered_students = set() unregistered_students = set() for stu in", "about the requested page # @variables: # s - the", "- get designation object of student holds_desig - get hold_desig", "= Get credit details from forms and the append it", "else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value)", "1 # s.room_no = \"\" # s.save() # else: #", "the student user_details - the rollno of the student required", "required to add exam timetable Dean - the extraInfo objects", "15, 'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text =", "get_context(request): \"\"\" This function gets basic gata from database to", "@csrf_exempt def addMinute(request): # \"\"\" # to add a new", "new batch. It checkes the authentication of the user and", "Exception as e: batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = []", "deleteMinute(request): # \"\"\" # to delete an existing senate meeting", "sheet.write_string('C'+str(k),name,normaltext) sheet.write_string('D'+str(k),dep,normaltext) k+=1 book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel')", "else: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=False, ) new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break", "- the rollno of the student # batch - the", "i.course_id not in choices: # i.acad_selection = False # i.save()", "faculty list from database @param: request - contains metadata about", "adds the basic profile information like username,password, name, # rollno,", "sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save() #", "about the requested page # pk - the primary key", "None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum = Curriculum.objects.select_related().filter(branch", "get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/')", "grades of the student @param: request - contains metadata about", "print(request.POST) # choices = request.POST.getlist('choice') # for i in choices:", "mother = request.POST.get('mother') # add = request.POST.get('address') # hall =", "# d = data.split(\"-\") # id = d[0] # course", "= ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme') # batch = request.POST.get('batch')", "{ # 'name': name, # 'rollno': roll.id, # 'programme': programme,", "HttpResponseRedirect('/aims/')# #################################################### # # ##########covenors and coconvenors################## # @csrf_exempt def", "template @param: request - contains metadata about the requested page", "request - contains metadata about the requested page. @variables: acadTtForm", "senate meeting minute object to the database. # @param: #", "student from the database # @param: # request - contains", "curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses =", "report after pre-registration @param: request - contains metadata about the", "= Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) #", "= request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses =", "# result = request.POST.get('designation') # hDes = HoldsDesignation() # hDes.user", "= 1 # s.room_no = \"\" # s.save() # else:", "sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp", "timetable, 'tab_id' :['10','2'] } examTtForm = ExamTimetableForm() if request.method ==", "# 'phoneno': ph, # 'batch': batch # } # print(data)", "# mother = request.POST.get('mother') # add = request.POST.get('address') # hall", "- designation for Acadadmin final_user - final designation of request", "import (Calendar, Course, Exam_timetable, Grades, Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum)", "father - father's name of the student # rollno -", "| Student.objects.filter(programme = \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark =", "request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list() courses = Course.objects.all() course_type =", "in unregistered_students: z = [] z.append(m) m += 1 z.append(i.id.user.username)", "import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm,", "'curriculum': curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else:", "= \"sem_\"+\"1\" # sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9):", "request.method == \"POST\": data = request.POST['delete'] t = Exam_timetable.objects.get(exam_time_table=data) t.delete()", "# t - the minute object received from id to", "sem_cred.append(request.POST.getlist(sem)[0]) # for i in range(1, 9): # sem =", "designation object of Co Convenor # result - the data", "designation, # } # return JsonResponse(data)# ###################################################### # # ##########Senate", "normaltext - formatting variable for normal text sheet - xlsx", "= Designation.objects.all().filter(name='Upper Division Clerk') # temp = HoldsDesignation.objects.all().filter(designation = desig_id).first()", "extraInfor objects exam_t - all the exam timetable objects timetable", "# 'courses': courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, #", "# print(k) # final_user = k[2] # if (str(acadadmin) !=", "formatted array/variable output - io Bytes object to write to", "requested page. # @variables: # choices - selected addtional courses", "i in to_date] to_date = datetime.datetime(*to_date).date() get_calendar_details = Calendar.objects.all().filter(description=prev_desc).first() get_calendar_details.description", "sem_id) courses = [] for course_slot in course_slots: courses +=", "student.address = str(hall) + \" \" + str(room) # student.save()", "# hDes = HoldsDesignation.objects.filter(user = student.user) # designation = []", "variable data k -temporary array to add data to formatted", "# acadmic admin to update the additional courses # @param:", "- designation object of Co Convenor # result - the", "= p # hDes.save() # data = { # 'name':", "s.delete() # e.delete() # u.delete() # return JsonResponse(data)# ######################################################### #", "django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from django.contrib.auth.decorators import", "the details of the required user. # \"\"\" # current_user", "# father = request.POST.get('father') # mother = request.POST.get('mother') # add", "# choices = request.POST.getlist('choice') # for i in choices: #", "sem_id = Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots =", "p = Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes", "basic profile information like username,password, name, # rollno, etc of", "if \"optional_\"+str(i) in request.POST: optional=True else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception", "course_id - course_id from database credits - credits from form.REQUEST", "= True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval = False) assistant_approve_list = AssistantshipClaim.objects.filter(ta_supervisor_remark", ".forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import (Calendar, Course,", "contains metadata about the requested page. @variables: data - data", "\"\" request_branch = \"\" request_programme = \"\" request_sem = \"\"", "= ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins)", "course_slots: courses += course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration(", "course_type=course_type, ) new_curr.append(ins) else: break i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch", "mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first() if", "added in the student course - course ofwhich the grade", "student.programme, # 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') #", "in hDes: # if des.designation == s or des.designation ==", "request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No faculty\") else: flot", "data of next semester courses courses - all the courses", "date for the academic caldendar event. desc - Description for", "- create registeration object in registeration table \"\"\" if user_check(request):", "is available # mother - mother's name of the student", "the grades of the student @param: request - contains metadata", "details form database ins - Inster data in database \"\"\"", "database stud_data - new student object created in database desig", "= \"PhD\") assistant_list = AssistantshipClaim.objects.filter(ta_supervisor_remark = True).filter(thesis_supervisor_remark = True).filter(hod_approval =True).filter(acad_approval", "display it on the page. @param: request - contains metadata", "metadata about the requested page @variables: batch - gets the", "if specialization == \"\": specialization=\"None\" if hall_no == None: hall_no=3", "get_object_or_404(Designation, name=\"Co Convenor\") # student = get_object_or_404(ExtraInfo, id=pk) # hDes", "'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm = AcademicTimetableForm() if request.method", "ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True)", "Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id, semester_id__semester_no=sem) registered_students = set()", "to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date", "# s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') #", "# \"\"\" # to add a new student convenor/coconvenor #", "contains metadata about the requested page # @variables: # data", "# hDes.delete() # return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')#", "student required to check if the student is available desig_id", "# \"\"\" # to add a new senate meeting minute", "faculty = list(chain(f1,f2,f3)) faculty_list = [] for i in faculty:", "= Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all()", "title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl.", "curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list =", "@login_required def add_curriculum(request): \"\"\" This function is used to add", "for i in range(1, 10): # sem = \"sem_\"+\"1\" #", "the requested page # @variables: # data - the id", "4, 6, 8] else: course_list_2 = [1, 3, 5, 7]", "= Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user, working=user, designation=desig, ) sem_id", "is used to check the type of user. It checkes", "convenor # student - the student object with the given", "of student from file user - new user created in", "Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() #print (temp) #", "\"\" request_programme = \"\" request_sem = \"\" #for checking if", "temp.working # k = str(user_details).split() # print(k) # final_user =", "Description for the academic calendar event. c = object to", "if (str(acadadmin) != str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # if request.method", "fetches the available data from the databases to display it", "# programme = request.POST.get('programme') # batch = request.POST.get('batch') # ph", "the form to add a senate meeting minutes acadTtForm -", "student's address subject - subject of which the grade has", "for i in registered_students: z = [] z.append(m) m +=", "i in from_date] from_date = datetime.datetime(*from_date).date() to_date = to_date[0].split('-') to_date", "- all the extraInfor objects exam_t - all the exam", "Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i in curriculum:", "\"ais/ais.html\", context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\"", "examTtForm - the form required to add exam timetable Dean", "desc - Description for the academic calendar event. c =", "render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty list", "\"\" # s.save() # else: # return HttpResponse(\"Data Does Not", "\"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem =", "specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch']", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to", "request_batch = \"\" request_branch = \"\" request_programme = \"\" if", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') try: batch = request.POST['batch'] course", "HttpResponse(\"TimeTable Deleted\") @login_required def add_calendar(request): \"\"\" to add an entry", "create registeration object in registeration table \"\"\" if user_check(request): return", "if(course_list[0]==1): course_list_2 = [2, 4, 6, 8] else: course_list_2 =", "sem and store data in databsae. User must be logged", "rendered titletext - formatting variable of title text dep -", "\"POST\": i=1 while True: if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\"", "list the type of courses \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/')", "# pk - the primary key of that particular student", "django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register, InitialRegistration, course_registration,", "request - contains metadata about the requested page @variables: current_user", "# 'designation': designation, # } # return JsonResponse(data)# ###################################################### #", "min_cred(request): # \"\"\" # to set minimum credit for a", "fathers_name - details of student from file mothers_name - details", "objects that holds the designation as a coconvenor meetings -", "It verify the grades of the student @param: request -", "# request - contains metadata about the requested page #", "\"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty list from", "render(request, \"ais/ais.html\", context) # #################################### # # curriculum # #", "# if request.method == \"POST\": # programme=request.POST['programme'] # batch=request.POST['batch'] #", "next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' :", "optional - optional from form.REQUEST course_type - course_type from form.REQUEST", "father's name of the student # rollno - the rollno", "get_object_or_404, render from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt", "department=DepartmentInfo.objects.all().filter(name=dept).first() if specialization == \"\": specialization=\"None\" if hall_no == None:", "- gets the details of the required user. # desig_id", "print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') #", "# \"\"\" # if request.method == \"POST\": # data =", "# course.save() # courses = Course.objects.all() # for i in", "# s - the designation object that contains senator #", "# student.address = str(hall) + \" \" + str(room) #", "get_calendar_details.to_date = to_date get_calendar_details.save() except Exception as e: from_date=\"\" to_date=\"\"", "No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15)", "HttpResponseRedirect('/academic-procedures/') # return HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic", "This function is used to add new curriculum in database", "acad admin # s - the student object from the", "sem=sem)): # s = Grades.objects.filter(student_id=id, sem=sem) # for p in", "faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to float", "user. # desig_id - to check the designation of the", "for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id = batch_id)", "@variables: # choices - selected addtional courses by the academic", "from form.REQUEST course_id - course_id from database credits - credits", "# convenor or coconvenor # hDes - holdsDesignation object to", "set() for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id =", "page @variables: dele - data being deleted from database \"\"\"", "- selected addtional courses by the academic person. # course", "9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] #", "Semester from form curriculum - Get data about curriculum from", "- the form required to add exam timetable exam_t -", "= \"\" # s.save() # else: # return HttpResponse(\"Data Does", "rollno - rollno of the student to become the convenor/coconvenor", "{} # return JsonResponse(data) # else: # father = request.POST.get('father')", "about the requested page. @variables: f1,f2,f3 - temporary varibles faculty", "from file dob - details of student from file fathers_name", "metadata about the requested page. @variables: data - data of", "= desig_id).first() # print (temp) # print (current_user) # acadadmin", "database # @param: # request - contains metadata about the", "= request.POST.get('batch') # ph = request.POST.get('phoneno') # if not Student.objects.filter(id=roll).exists():", "# student.save() # s = Student.objects.get(id=student) # s.father_name=father # s.mother_name=mother", "id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"] if", "course_code=i.course_code, course_id=i.course_id, credits=i.credits, optional=i.optional, course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum", "from request user_details - extract details of user from database", "table # @variables: # e - the extraInfo objects of", "excel - excel file sheet - sheet no in excel", "@variables: # data - the id of the minute object", "hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym =", "@login_required def curriculum(request): \"\"\" This function is used to see", "[] for i in faculty: faculty_list.append(i) return faculty_list @login_required def", "generates semester grade sheet @variables: now - current datetime month", "try: batch = request.POST['batch'] course = Courses.objects.get(id = request.POST['course']) obj", "def generate_preregistration_report(request): \"\"\" to generate preresgistration report after pre-registration @param:", "\"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book = Workbook(output,{'in_memory':True})", "the outdated exam timetable. @param: request - contains metadata about", "# sem_cred = Get credit details from forms and the", "the user # sem - current semester of the student", "request - contains metadata about the requested page @variables: batch", "faculty of data faculty_list - list of faculty \"\"\" try:", "db.programme = programme # st.phone_no = ph # db.save() #", "from file last_name - details of student from file email", "'center', 'valign': 'vcenter'}) normaltext = book.add_format({'bold': False, 'font_size': 15, 'align':", "acad admin # father - father's name of the student", "details of student from file category - details of student", "that the particular student is a convenor/coconvenor to be deleted", "pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional", "data to database # def curriculum(request): # ''' def delete_advanced_profile(request):", "name of the student user_details - the rollno of the", "delete the outdated timetable from the server. @param: request -", "remove a convenor/coconvenor from the position # @param: # request", "import Batch @login_required def user_check(request): \"\"\" This function is used", "# information that the particular student is a senator #", "json import os import xlrd import logging from io import", "required user. # desig_id - used to check the designation", "Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course as", "# batch = request.POST.get('batch') # ph = request.POST.get('phoneno') # if", "for new batch. It checkes the authentication of the user", "# 'course_type' : course_type, # 'curriculum' : curriculum, # 'tab_id'", "from form.REQUEST course_type - course_type from form.REQUEST ins - data", "details of the required user. # desig_id - used to", "@variables: # current_user - details of the current user. #", "about the requested page @variables: programme - programme from form.REQUEST", "= request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj =", "student from file category - details of student from file", ") new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) elif request.POST['option'] == '2': new_curriculum=[] for i", "str(user_details).split() # print(k) # final_user = k[2] # if (str(acadadmin)", "advance information of the student # @param: # request -", "the database. # @param: # request - contains metadata about", "course_type, # 'curriculum' : curriculum, # 'tab_id' :['3','1'] # }", "a coconvenor meetings - the all meeting objects held in", "\"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle)", "logging from io import BytesIO from xlsxwriter.workbook import Workbook from", "5, 7] else: return [2, 4, 6, 8] @login_required def", "table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1']", "= request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch =", "Constants.COURSE_TYPE context= { 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'faculty_list':", "{ # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name,", "= request.POST['branch'] request_programme = request.POST['programme'] except Exception as e: request_batch", "of the student # s - the student object of", "the academic caldendar event. desc - Description for the academic", "desc = request.POST.getlist('description')[0] from_date = from_date[0].split('-') from_date = [int(i) for", "HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set minimum credit", "hidden in the webpage # \"\"\" # s = get_object_or_404(Designation,", "context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request): \"\"\" to", "# 'designation': hDes.designation.name, # } # return JsonResponse(data) # else:", "= Course.objects.all() course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj =", "try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme = request.POST['programme']", "e: request_batch = \"\" request_branch = \"\" request_programme = \"\"", "Exist\") # return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\"", "request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-')", "exam_t = \"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm':", "details of student from file fathers_name - details of student", "object that contains convenor # c - the designation object", "@variables: examTtForm - data of delete dictionary in post request", "to_date = [int(i) for i in to_date] to_date = datetime.datetime(*to_date).date()", "of student from file fathers_name - details of student from", "+= course_slot.courses.all() new_reg=[] for c in courses: reg=course_registration( course_id =", "if the student is available # mother - mother's name", "hall no of where the student stays # room no", "authentication of the user. @param: request - contains metadata about", "else: # data = {} # return JsonResponse(data) # else:", "'assistant_list_length' : assistant_list_length, 'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date':", "@variables: sem - get current semester from current time now", "object that contains senator # student - the list students", "!= str(final_user)): # return HttpResponseRedirect('/academic-procedures/') # print(request.POST['delete']) # data =", "context) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "the student object of the student # \"\"\" e =", "float_course(request): \"\"\" to float courses for the next sem and", "if hall_no == None: hall_no=3 else: hall_no=int(hall_no) programme_name=request.POST['Programme'] batch_year=request.POST['Batch'] batch", "[] for i in obj: if i.student_id.batch_id.year == int(batch): registered_courses.append(i)", "output \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\":", "room no - hostel room no # \"\"\" current_user =", "st.phone_no = ph # db.save() # st.save() # data =", "new event to the academic calendar. \"\"\" if user_check(request): return", "desig_id - checking the designation of the current user #", "check the type of user. It checkes the authentication of", "for the previous event which is to be updated. get_calendar_details", "== course): # print(p.course_id) # p.delete() # else: # return", "check for designation acadadmin - designation for Acadadmin final_user -", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # print(request.POST) # rollno=request.POST.get('roll')", "metadata about the requested page @variables: acadTtForm - the form", "- all the academic timetable objects calendar - all the", "information like username,password, name, # rollno, etc of a student", "# p.delete() # else: # return HttpResponse(\"Unable to delete data\")", "mothers_name, cpi = 0, category = category, hall_no = hall_no,", "import (CourseSlot, Course as Courses, Batch, Semester, Programme, Discipline) from", "\"\"\" to generate Course List of Registered Students @param: request", "\"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete the", "# for p in s: # if (str(p.course_id) == course):", "courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','1'] } return render(request,", "- Description for the academic calendar event. prev_desc - Description", "the current user. # desig_id - to check the designation", "sheet = book.add_worksheet() title_text = ((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2',", "'1': new_curriculum=[] for i in curriculum: ins=Curriculum( programme=i.programme, batch=i.batch+1, branch=i.branch,", "# mother - mother's name of the student # add", "courses - get courses from database courses_type - get course", "from form.REQUEST branch - branch from form.REQUEST sem - semester", "form form curriculum - curriculum details form database ins -", "It adds the basic profile information like username,password, name, #", "return render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function", "department - all the departments in the college attendance -", "Formatted Array to be converted to xlsx k -temporary array", "table(any type of) of the semester. @param: request - contains", "batch_year=request.POST['Batch'] batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year", "\"\"\" acad-admin can delete the outdated exam timetable. @param: request", "render(request, \"ais/ais.html\", context) return HttpResponse(obj,content_type='application/json') else: return render(request, \"ais/ais.html\", context)", "about the requested page. @variables: examTtForm - data of delete", "2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum", "\"\"\" # current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first()", "= st return response @login_required def add_new_profile (request): \"\"\" To", "xlsx file book - workbook of xlsx file title -", "from database ans - Formatted Array to be converted to", "return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")", "# 'name': name, # 'rollno': roll.id, # 'programme': programme, #", "'assistant_list' : assistant_list, 'assistant_approve_list' : assistant_approve_list, 'assistant_list_length' : assistant_list_length, 'tab_id':", "- curriculum details form database ins - Inster data in", "'curriculum_course': curriculum_courses, # } # return render(request, \"ais/ais.html\", context) #", "available data from the databases to display it on the", "- data of the student to be hidden in the", "hall = request.POST.get('hall') # room = request.POST.get('room') # cpi =", "- father's name of the student # user_details - the", "dele.delete() curriculum = Curriculum.objects.select_related().filter(branch = request.POST['branch']).filter(batch = request.POST['batch']).filter(programme= request.POST['programme']) courses", "from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect, JsonResponse", "Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() acadadmin =", "HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass", "# if not Student.objects.filter(id=roll).exists(): # db = Student() # st", "# else: # hDes.designation = p # hDes.save() # data", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == 'POST': programme =", "request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') #", "p in s: # if (str(p.course_id) == course): # print(p.course_id)", "- branch from form.REQUEST sem - semester from form.REQUEST course_code", "the student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user", "Workbook from xhtml2pdf import pisa from itertools import chain from", "# # ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" #", "up the homepage of the application. It checkes the authentication", "= dept, year = batch_year).first() user = User.objects.create_user( username=roll_no, password='<PASSWORD>',", "book.close() output.seek(0) response = HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment;", "is enrolled in # ph - the phone number of", "faculty_list = get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context=", "the student # roll - the rollno of the student", "the time table(any type of) of the semester. @param: request", "data = { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id, #", "= Student.objects.get(id=extraInfo) # data = { # 'name': extraInfo.user.username, #", "minute object to be deleted # t - the minute", "t.delete() return HttpResponse(\"TimeTable Deleted\") @login_required def delete_exam_timetable(request): \"\"\" acad-admin can", "= get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= {", "a new student senator # @param: # request - contains", "def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\" # to", "selected addtional courses by the academic person. # course -", "pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm, 'courses': courses,", "- contains metadata about the requested page. @variables: from_date -", "e.user.username) # s = get_object_or_404(Student, id=e) # data = {", "the requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) #", "can upload the exam timtable of the ongoing semester. @param:", "SuccessFully\") @login_required def verify_grade(request): \"\"\" It verify the grades of", "stu = arr[0] # if Student.objects.get(id=stu): # s = Student.objects.get(id=stu)", "einfo - new extrainfo object created in database stud_data -", "Student.objects.create( id=einfo, programme = programme_name, batch=batch_year, batch_id = batch, father_name", "in faculty: faculty_list.append(i) return faculty_list @login_required def float_course(request): \"\"\" to", "sheet no in excel file roll_no - details of student", "of the logged in user # user_details - the details", "in senator meetings minuteForm - the form to add a", "optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch, sem=sem, course_code=course_code, course_id=course_id,", "- mother's name of the student # add - student's", "db.batch = batch # db.programme = programme # st.phone_no =", "id=request.POST.getlist(\"senate_id\")[0]) # hDes = get_object_or_404( HoldsDesignation, user = student.user) #", "mothers_name - details of student from file category - details", "num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\" \"+str(c) temp =", "the student acadadmin - student's address subject - subject of", "'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' :", "'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request):", "[] z.append(m) m += 1 z.append(i.id.user.username) z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered')", "object to write to xlsx file book - workbook of", "import chain from django.contrib.auth.models import User from django.http import HttpResponse,", "= ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp =", "get_faculty_list() courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses':", "being deleted from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={", "# to delete the advance information of the student #", "to generate Course List of Registered Students @param: request -", "final output b - temporary variables for final output c", "'POST': programme = request.POST['programme'] now = datetime.datetime.now() year = int(now.year)", "i+=1 Curriculum.objects.bulk_create(new_curr) curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme)", "# @variables: # e - the extraInfo objects of the", "no - hostel room no # \"\"\" current_user = get_object_or_404(User,", "extraInfo objects that holds the designation as a coconvenor meetings", "= get_object_or_404(User, username=request.user.username) user_details = ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division", ") new_curr_inst.append(ins) Curriculum_Instructor.objects.bulk_create(new_curr_inst) else: break i+=1 return render(request, \"ais/ais.html\", context)", "context) return render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This", "if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course", "students as a senator extra - all the extraInfor objects", "addtional courses by the academic person. # course - Course", "inst = get_object_or_404(User, username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if", "this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list", "user - new user created in database einfo - new", "\"\" if request_batch == \"\" and request_branch == \"\" and", "float courses for the next sem and store data in", "HttpResponseRedirect('/academic-procedures/') def add_optional(request): # \"\"\" # acadmic admin to update", "senator # student - the list students that is a", "programme = request.POST['programme'] now = datetime.datetime.now() year = int(now.year) batch", "metadata about the requested page # @variables: # current_user -", "courses, # 'course_type': course_type, # 'curriculum_course': curriculum_courses, # } #", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def float_course_submit(request):", "ins - Inster data in database \"\"\" if user_check(request): return", "final output c - temporary variables for final output st", "} return context @login_required def homepage(request): \"\"\" This function is", "k -temporary array to add data to formatted array/variable output", "person. # course - Course details which is selected by", "== 2: sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1", "# sem = int(d[3]) # if request.method == \"POST\": #", "from_date = request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] from_date", "object of Convenor # p - designation object of Co", "context) return render(request, \"ais/ais.html\", context) @login_required def add_exam_timetable(request): \"\"\" acad-admin", "Curriculum_Instructor,Constants, Meeting, Student, Student_attendance, Timetable,Curriculum) from applications.programme_curriculum.models import (CourseSlot, Course", "current semester that a student must take # @param: #", "django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import", "s - designation object of senator # hDes - holdsDesignation", "= 1 for i in data: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c =", "branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in request.POST:", "delete the outdated exam timetable. @param: request - contains metadata", "== \"POST\": # st = request.POST['delete'] # arr = st.split(\"-\")", "student - the list students that is a senator #", "request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for i in", "context) return render(request, \"ais/ais.html\", context) @login_required def delete_curriculum(request): \"\"\" This", "s = Designation.objects.get(name='Convenor') # p = Designation.objects.get(name='Co Convenor') # if", "name, # 'rollno': roll.id, # 'programme': programme, # 'phoneno': ph,", "# if not student: # data = {} # return", "in ans: sheet.write_number('A'+str(k),num,normaltext) num+=1 z,b,c = str(i[0]),i[1],i[2] name = str(b)+\"", "programme = programme_name, batch=batch_year, batch_id = batch, father_name = fathers_name,", "-temporary array to add data to formatted array/variable output -", "batch=\"\" course=\"\" curr_key=\"\" obj=\"\" registered_courses = [] for i in", "p - designation object of Co Convenor # result -", "course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch", "curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem)", "details of student from file dob - details of student", "the exam timetable objects timetable - all the academic timetable", "entry.course_code=course_code entry.course_id=course_id entry.credits=credits entry.optional=optional entry.course_type=course_type entry.save() curriculum = Curriculum.objects.select_related().filter(branch =", "username of the logged in user # user_details - the", "- formatting variable for normal text sheet - xlsx sheet", "grades = Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, #", "the academic calender objects department - all the departments in", "course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass ins=Curriculum( programme=programme, batch=batch, branch=branch,", "# exam_t = Exam_timetable.objects.all() procedures_context = acad_proced_global_context() try: examTtForm =", "try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all()", "'POST': # print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] #", "batch form form curriculum - curriculum details form database ins", "print(student.address) # if not student: # data = {} #", "data = request.POST['delete'] t = Timetable.objects.get(time_table=data) t.delete() return HttpResponse(\"TimeTable Deleted\")", "data of delete dictionary in post request timetable - all", "current time year - getcurrent year batch - gets the", "in database It checkes the authentication of the user and", "- contains metadata about the requested page @variables: programme -", "curriculum, 'tab_id' :['3','2'] } return render(request, \"ais/ais.html\", context) else: return", "form curriculum - Get data about curriculum from database courses", "semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester = sem_id) courses =", "a new student convenor/coconvenor # @param: # request - contains", "student # user_details - the rollno of the student required", "\"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details = ExtraInfo.objects.all().filter(user=current_user).first() #", "with the given pk # hDes - the holdDesignation object", "if Student.objects.get(id=stu): # s = Student.objects.get(id=stu) # s.father_name = \"\"", "== c: # designation = des.designation.name # des.delete() # data", "id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\"", "= get_object_or_404(Designation, name=\"Convenor\") c = get_object_or_404(Designation, name=\"Co Convenor\") # student", "= Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list = Courses.objects.all() course_type =", "# print(curriculum_courses) # courses = Course.objects.all() # course_type = Constants.COURSE_TYPE", "= request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch =", "return HttpResponseRedirect('/aims/') # # return JsonResponse(data) # else: # return", "k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book =", "from database @param: request - contains metadata about the requested", "sem) # print(curriculum_courses) # courses = Course.objects.all() # course_type =", "faculty_list = [] for i in faculty: faculty_list.append(i) return faculty_list", "= ExamTimetableForm() # acadTtForm = AcademicTimetableForm() # calendar = Calendar.objects.all()", "request.POST['branch'] request_programme = request.POST['programme'] except Exception as e: request_batch =", "fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value) phone_no=int(sheet.cell(i,9).value) address=str(sheet.cell(i,10).value) dept=str(sheet.cell(i,11).value) specialization=str(sheet.cell(i,12).value) hall_no=sheet.cell(i,13 ).value department=DepartmentInfo.objects.all().filter(name=dept).first()", "curriculum. It checkes the authentication of the user and also", "ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Senator') # hDes = HoldsDesignation() #", "result == \"Convenor\": # hDes.designation = s # else: #", "the batch from form sem - stores the next semester", "course details # \"\"\" # current_user = get_object_or_404(User, username=request.user.username) #", "about the requested page @variables: senates - the extraInfo objects", "the academic calendar to be updated. @param: request - contains", "data\") return HttpResponse(\"Data Deleted SuccessFully\") @login_required def verify_grade(request): \"\"\" It", "the position # @param: # request - contains metadata about", "delete_curriculum(request): \"\"\" This function is used to delete curriculum entry", "filename = ' + course.code + '.xlsx' response['Content-Disposition'] = st", "of student from file category - details of student from", "Semester from form \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context= {", "request.method == 'POST' and request.FILES: acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if", "} return render(request, \"ais/ais.html\", context) context= { 'tab_id' :['3','1'] }", "add details of new upcoming students in the database.User must", "to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date", "acadTtForm = AcademicTimetableForm(request.POST, request.FILES) if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\",", "e: programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\"", "return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin can", "dean student - the students as a senator extra -", "of where the student stays # room no - hostel", "entry.save() curriculum = Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses", "object in registeration table \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') context=", "= request.POST.getlist('from_date') to_date = request.POST.getlist('to_date') desc = request.POST.getlist('description')[0] prev_desc =", "# data = {} # return JsonResponse(data) # @csrf_exempt def", "} # return JsonResponse(data) # else: # data = {}", "\"ais/ais.html\", context) # #################################### # # curriculum # # ####################################", "- contains metadata about the requested page @variables: dele -", "requested page # @variables: # current_user - gets the data", "that the particualr student is holding the senator designation #", "((str(course.name)+\" : \"+str(str(batch)))) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll", "= ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation", "objects held in senator meetings minuteForm - the form to", "return render(request, \"ais/ais.html\", context) # else: # return render(request, \"ais/ais.html\")", "acadTtForm = AcademicTimetableForm() calendar = Calendar.objects.all() this_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses", "in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits =", "c = Calendar( from_date=from_date, to_date=to_date, description=desc) c.save() HttpResponse(\"Calendar Added\") return", "Curriculum.objects.select_related().get(curriculum_id=request.POST[str(i)+\"_ccode\"]) flot.floated = True flot.save() new_curr_inst=[] for c,i in enumerate(request.POST.getlist(str(i)+'_fac')):", "# hall - hall no of where the student stays", "request.method == \"POST\": # if(Grades.objects.filter(student_id=id, sem=sem)): # s = Grades.objects.filter(student_id=id,", "\"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id) #", "room = request.POST.get('room') # cpi = request.POST.get('cpi') # student.address =", "temporary variables for final output b - temporary variables for", "the details of the current user # desig_id - checking", "== \"\" and request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all()", "and request_programme==\"\": curriculum = None #Curriculum.objects.all() else: sem = sem_for_generate_sheet()", "True) assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for", "request.method == 'POST': programme = request.POST['programme'] now = datetime.datetime.now() year", "user = get_object_or_404(User, username = e.user.username) # s = get_object_or_404(Student,", "z.append(str(i.id.user.first_name)+\" \"+str(i.id.user.last_name)) z.append(i.id.department.name) z.append('registered') data.append(z) output = BytesIO() book =", "the semester. @param: request - contains metadata about the requested", "prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for", "to set minimum credit for a current semester that a", "# return HttpResponse('not uploaded') # return render(request, \"ais/ais.html\", {}) def", "for i in courses: # if i.course_id not in choices:", "== 'POST': # rollno = request.POST.get('rollno_convenor') # extraInfo = ExtraInfo.objects.get(id=rollno)", "sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4 num", "if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"] == \"\" : logging.warning(\"No", "sheet - xlsx sheet to be rendered titletext - formatting", "databsae. User must be logged in and must be acadadmin", "programme) if request.POST['option'] == '1': new_curriculum=[] for i in curriculum:", "student senator # @param: # request - contains metadata about", "= [int(i) for i in from_date] from_date = datetime.datetime(*from_date).date() to_date", "if str(i)+\"_ccode\" in request.POST: if str(i)+\"_fac\" in request.POST: if request.POST[str(i)+\"_fac\"]", "'curriculum': curriculum, 'pgstudent' : pgstudent, 'assistant_list' : assistant_list, 'assistant_approve_list' :", "return HttpResponseRedirect('/aims/') # else: # return HttpResponseRedirect('/aims/')# #################################################### # #", "phone_no - details of student from file address - details", "faculty_list, 'tab_id' :['5','1'] } return render(request, \"ais/ais.html\", context) else: return", "# s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/') #", "extra - all the extraInfor objects exam_t - all the", "course_id from database credits - credits from form.REQUEST optional -", "minute object received from id to be deleted # \"\"\"", "sem - get current semester from current time now -", "for the academic calendar event. c = object to save", "course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context)", "admin. # \"\"\" if request.method == \"POST\": pass # print(request.POST)", "to_date] to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\"", "context @login_required def homepage(request): \"\"\" This function is used to", "convenor CoConvenor - the extraInfo objects that holds the designation", "'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum': curriculum,", "django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render", "request.FILES) if examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return", "== \"POST\": # curr_id=request.POST['course'] # print(curr_id) # curr_course = Curriculum.objects.filter(curriculum_id=curr_id)", "\"\"\" now = datetime.datetime.now() month = int(now.month) if month >=", "the requested page @variables: batch - gets the batch course", "== \"Convenor\": # hDes.designation = s # else: # hDes.designation", "the batch course - gets the course curr_key - gets", "examTtForm.is_valid(): examTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request, \"ais/ais.html\",", "render(request, \"ais/ais.html\", context) #Generate Attendance Sheet def sem_for_generate_sheet(): \"\"\" This", "return HttpResponseRedirect('/academic-procedures/') # if request.method == 'POST' and request.FILES: #", "counter for Sl. No (in formated data) z - temporary", "Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year = batch_year).first() user", "s.room_no = room # s.save() # return HttpResponseRedirect('/academic-procedures/') # return", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') context={ 'tab_id' :['3','2'] } if request.method", "from xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from itertools", "= request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i) for i", "context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\" acad-admin", "\"\" timetable = \"\" exam_t = \"\" pass context =", "\"\"\" if request.method == \"POST\": pass # print(request.POST) # choices", "get_template from django.views.decorators.csrf import csrf_exempt from django.template.loader import render_to_string from", "grade of the student # @param: # request - contains", "from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\" This function", "request_programme).filter(sem= request_sem) # context={ # 'courses' : courses, # 'course_type'", "curriculum for new batch. It checkes the authentication of the", ": account_flag } return context @login_required def homepage(request): \"\"\" This", "des.designation == c: # designation = des.designation.name # des.delete() #", "desc - Description for the academic calendar event. prev_desc -", "the grade has to be added sem - semester of", "batch=request.POST['AddBatch'] branch=request.POST['AddBranch'] sem=request.POST[\"semester_\"+str(i)] course_code=request.POST[\"course_code_\"+str(i)] course_name=request.POST[\"course_name_\"+str(i)] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits_\"+str(i)] if \"optional_\"+str(i) in", "== int(batch): registered_courses.append(i) ans = [] for i in registered_courses:", "applications.academic_procedures.views import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request):", "assistant_flag, 'hod_flag' : hod_flag, 'account_flag' : account_flag } return context", "roll_no - details of student from file first_name - details", "= [] for course_slot in course_slots: courses += course_slot.courses.all() new_reg=[]", "curriculum course_type - list the type of courses \"\"\" if", "used to decide curriculum for new batch. It checkes the", "[] m = 1 for i in unregistered_students: z =", "to be displayed in the webpage # \"\"\" s =", "def add_basic_profile(request): # \"\"\" # It adds the basic profile", "- contains metadata about the requested page @variables: batch -", "Designation.objects.get(name='Co Convenor') # result = request.POST.get('designation') # hDes = HoldsDesignation()", "primary key of that particular student field # @variables: #", "# return HttpResponse(\"Data Does Not Exist\") # return HttpResponse(\"Data Deleted", "become # convenor or coconvenor # hDes - holdsDesignation object", "# return HttpResponse(\"Data Deleted Successfully\") def add_advanced_profile(request): # \"\"\" #", "# @csrf_exempt def add_convenor(request): # \"\"\" # to add a", "the departments in the college attendance - all the attendance", "request.POST: # s = get_object_or_404(Designation, name=\"Senator\") # student = get_object_or_404(ExtraInfo,", "the requested page # pk - the primary key of", "# } courses = Course.objects.all() course_type = Constants.COURSE_TYPE html =", "designation object that contains senator # student - the list", "the requested page # @variables: # current_user - gets the", "if not student: # data = {} # return JsonResponse(data)", "# return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\"", "that rollno # s - designation object of senator #", "data - the id of the minute object to be", "- programme from form.REQUEST batch - batch from form.REQUEST branch", "from_date[0].split('-') from_date = [int(i) for i in from_date] from_date =", "# # #################################### @login_required def curriculum(request): \"\"\" This function is", "current time now - get current time year - getcurrent", "= get_object_or_404( HoldsDesignation, user = student.user) # hDes.delete() # return", "the students as a senator extra - all the extraInfor", "# print(request.POST, \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\") # rollno = request.POST.getlist('Roll Number')[0] # #", "in choices: # i.acad_selection = False # i.save() # return", "senator students - all the objects in the Student class", "student with that rollno # s - designation object of", "procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'],", "co convenor # student - the student object with the", "uploaded') # return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\"", "- details of student from file category - details of", "assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag = obj.account_status except", "to be converted to xlsx k -temporary array to add", "add new curriculum in database It checkes the authentication of", "user = User.objects.create_user( username=roll_no, password='<PASSWORD>', first_name=first_name, last_name=last_name, email=email, ) einfo", "} acadTtForm = AcademicTimetableForm() if request.method == 'POST' and request.FILES:", "str(\" \") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle)", "# add - student's address # cpi - student's cpi", "instance from the database for the previous Description. \"\"\" if", "# temp = HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) #", "required to check if the student is available desig_id -", "course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t =", "page @variables: sem - get current semester from current time", "list of faculty \"\"\" try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant", "Exception as e: f1=f2=f3=\"\" pass faculty = list(chain(f1,f2,f3)) faculty_list =", "xlsxwriter.workbook import Workbook from xhtml2pdf import pisa from itertools import", "the homepage of the application. It checkes the authentication of", "database It checkes the authentication of the user and also", "xlsx sheet to be rendered titletext - formatting variable of", "- mother 's name of the student # acadadmin -", "# current_user - father's name of the student # user_details", "if user_check(request): return HttpResponseRedirect('/academic-procedures/') course_list = sem_for_generate_sheet() if(course_list[0]==1): course_list_2 =", "extraInfo.user.username, # 'rollno_convenor': extraInfo.id, # 'designation': hDes.designation.name, # } #", "pk - the primary key of the student's record in", "extraInfo.user # if result == \"Convenor\": # hDes.designation = s", "sheet.set_column('E:E',30) k = 4 num = 1 for i in", "hDes.working = extraInfo.user # hDes.designation = s # hDes.save() #", "- get course types from database \"\"\" if user_check(request): return", "# sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1] # sem.save()", "desig_id - mother 's name of the student # acadadmin", "Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester =", "to remove a senator from the position # @param: #", "db.save() # st.save() # data = { # 'name': name,", "be updated. @param: request - contains metadata about the requested", "username = i) inst = ExtraInfo.objects.select_related('user','department').get(user=inst) if c==0: ins=Curriculum_Instructor( curriculum_id=flot,", "def min_cred(request): # \"\"\" # to set minimum credit for", "# batch=request.POST['batch'] # branch=request.POST['branch'] # sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch", "return render(request, \"ais/ais.html\", context) def get_faculty_list(): \"\"\" to get faculty", "verify the grades of the student @param: request - contains", "= Student.objects.filter(batch_id = batch_id) for stu in students: if stu", "This function gets basic gata from database to send to", "the particular student is a convenor/coconvenor to be deleted #", "database obj - get stdents data from database ans -", "= request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum = Curriculum.objects.select_related().filter(branch =", "import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render from", "page. @variables: data - data of delete dictionary in post", "year - current year batch - batch form form curriculum", "that holds the designation as a dean student - the", "of next semester courses courses - all the courses in", "exam_t, 'timetable': timetable, 'academic_calendar': calendar, 'next_sem_course': next_sem_courses, 'this_sem_course': this_sem_courses, 'curriculum':", "= \"\" this_sem_courses = \"\" next_sem_courses = \"\" courses =", "requested page @variables: current_user - get user from request user_details", "request user \"\"\" try: current_user = get_object_or_404(User, username=request.user.username) user_details =", "course_type=i.course_type, ) new_curriculum.append(ins) Curriculum.objects.bulk_create(new_curriculum) batch=batch+1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme", "add attendance data to database # def curriculum(request): # '''", "try: f1 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name", "used to check the type of user. It checkes the", "formatting variable of title text dep - temporary variables z", "try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"] course_name=request.POST[\"course_id\"] course_id=Course.objects.get(course_name=course_name) credits=request.POST[\"credits\"]", "rollno # s - designation object of senator # hDes", "\"\"\" This function is used to add new curriculum in", "get_faculty_list(): \"\"\" to get faculty list from database @param: request", "from file specialization - details of student from file hall_no", "semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg) else: return render(request, \"ais/ais.html\", context)", "the requested page # @variables: # current_user - details of", "False def get_context(request): \"\"\" This function gets basic gata from", "about the requested page. @variables: from_date - The starting date", "from_date=\"\" to_date=\"\" desc=\"\" pass c = Calendar( from_date=from_date, to_date=to_date, description=desc)", "ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') # temp =", "is selected by the academic admin. # \"\"\" if request.method", "required to add exam timetable exam_t - all the exam", "- student's address # cpi - student's cpi # hall", "student.user) # designation = [] # for des in hDes:", "# @variables: # current_user - gets the data of current", "also fetches the available data from the databases to display", "the name of the student # roll - the rollno", "page @variables: current_user - get user from request user_details -", "print(k) # final_user = k[2] # if (str(acadadmin) != str(final_user)):", "render(request, 'ais/ais.html', context) @login_required def next_curriculum(request): \"\"\" This function is", "- Object of time table to be deleted \"\"\" if", "k = 4 num = 1 for i in data:", "sem = sem[year-int(request_batch)-1] else: sem = sem[year-int(request_batch)] sem+=1 curriculum =", "name of the student # acadadmin - student's address #", "import acad_proced_global_context from applications.programme_curriculum.models import Batch @login_required def user_check(request): \"\"\"", "final_user = k[2] # if (str(acadadmin) != str(final_user)): # return", "'course_verification_date' : procedures_context['course_verification_date'], 'submitted_course_list' : procedures_context['submitted_course_list'], 'result_year' : procedures_context['result_year'], 'batch_grade_data'", "details of student from file specialization - details of student", "= Curriculum.objects.select_related().filter(branch = branch).filter(batch = batch).filter(programme= programme) courses = Course.objects.all()", "extraInfo = ExtraInfo.objects.get(id=rollno) # s = Designation.objects.get(name='Convenor') # p =", "optional=False course_type=request.POST[\"course_type\"] except Exception as e: id=\"\" programme=\"\" batch=\"\" branch=\"\"", "datetime.datetime.now() month = int(now.month) if month >= 7 and month", "# room no - hostel room no # \"\"\" current_user", "acadTtForm, 'examTtForm': examTtForm, 'courses': courses, 'courses_list': courses_list, 'course_type': course_type, 'exam':", "# acadadmin = temp.working # k = str(user_details).split() # print(k)", "# # view to add attendance data to database #", "database # def curriculum(request): # ''' def delete_advanced_profile(request): # \"\"\"", "- current date from system year - current year batch", ": \"+ batch.name + str(\" \") + batch.discipline.acronym + str(\"", "return HttpResponseRedirect('/academic-procedures/') context = get_context(request) return render(request, \"ais/ais.html\", context) #", "courses = \"\" course_type = \"\" timetable = \"\" exam_t", "# st = ExtraInfo.objects.get(id=roll.id) # db.name = name.upper() # db.id", "request - contains metadata about the requested page # pk", "hDes.designation = p # hDes.save() # data = { #", "- Get data about curriculum from database courses - get", "} if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch']", "= None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now()", "add a senate meeting minutes acadTtForm - the form to", "calendar - all the academic calender objects department - all", "requested rollno # \"\"\" current_user = get_object_or_404(User, username=request.user.username) # user_details", "for i in range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() #", "from file address - details of student from file department", "# course = Course.objects.all().filter(course_id=i).first() # course.acad_selection = True # course.save()", "date for the academic calendar event. to_date - The ending", "request - contains metadata about the requested page. @variables: f1,f2,f3", "calendar. \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') calendar = Calendar.objects.all() context=", "8] @login_required def generatexlsheet(request): \"\"\" to generate Course List of", "# 'id': pk, # 'designation': designation, # } # return", "specialization, curr_semester_no=sem, ) desig = Designation.objects.get(name='student') hold_des = HoldsDesignation.objects.create( user=user,", "position # @param: # request - contains metadata about the", "request.POST.getlist('description')[0] prev_desc = request.POST.getlist('prev_desc')[0] from_date = from_date[0].split('-') from_date = [int(i)", "- the minute object received from id to be deleted", "database courses - get courses from database courses_type - get", "- the student object with the given pk # hDes", "courses courses - all the courses in curriculum course_type -", "= Semester.objects.get(curriculum = batch.curriculum, semester_no = sem) course_slots = CourseSlot.objects.all().filter(semester", "student # s - the student object of the student", "\"ais/ais.html\", context) # # ---------------------senator------------------ # @csrf_exempt def senator(request): #", "the courses in curriculum course_type - list the type of", "True, 'font_size': 22, 'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold':", "student = get_object_or_404(ExtraInfo, id=pk) # hDes = HoldsDesignation.objects.filter(user = student.user)", "form required to add exam timetable exam_t - all the", "str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle)", "HttpResponseRedirect('/academic-procedures/') # if request.method == \"POST\": # curr_id=request.POST['course'] # print(curr_id)", "'tab_id': ['1','1'], 'context': procedures_context['context'], 'lists': procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'],", "\"ais/ais.html\", context) @login_required def edit_curriculum(request): \"\"\" This function is used", "HoldsDesignation() # hDes.user = extraInfo.user # hDes.working = extraInfo.user #", "student must take # @param: # request - contains metadata", "father's name of the student user_details - the rollno of", "\") + str(batch.year)) sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll", "= request.POST['delete'] # arr = st.split(\"-\") # stu = arr[0]", "stores the next semester obj - All the registration details", "roll.id, # 'programme': programme, # 'phoneno': ph, # 'batch': batch", "if acadTtForm.is_valid(): acadTtForm.save() return render(request, \"ais/ais.html\", context) else: return render(request,", "Sheet def sem_for_generate_sheet(): \"\"\" This function generates semester grade sheet", "def user_check(request): \"\"\" This function is used to check the", "== \"\": specialization=\"None\" if hall_no == None: hall_no=3 else: hall_no=int(hall_no)", "'tab_id' :\"2\" # } # return render(request,\"ais/ais.html\", context) # else:", "batch, father_name = fathers_name, mother_name = mothers_name, cpi = 0,", "database @param: request - contains metadata about the requested page.", "- all the academic calender objects department - all the", "file programme - details of student from file batch -", "request.POST.getlist('Roll Number')[0] # # print(request.POST.get('rollno')) # extraInfo = ExtraInfo.objects.get(id=rollno) #", "calendar event. to_date - The ending date for the academic", "Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses)", "else: optional=False course_type=request.POST[\"course_type_\"+str(i)] except Exception as e: programme=\"\" batch=\"\" branch=\"\"", "Constants.COURSE_TYPE # timetable = Timetable.objects.all() # exam_t = Exam_timetable.objects.all() procedures_context", "HttpResponse(output.read(),content_type = 'application/vnd.ms-excel') st = 'attachment; filename = ' +", "object of the new senator # data - data of", "request - contains metadata about the requested page. @variables: examTtForm", "the acad admin # s - the student object from", "sheet.set_default_row(25) sheet.merge_range('A2:E2', title_text, title) sheet.write_string('A3',\"Sl. No\",subtitle) sheet.write_string('B3',\"Roll No\",subtitle) sheet.write_string('C3',\"Name\",subtitle) sheet.write_string('D3',\"Discipline\",subtitle)", "# current_user - the username of the logged in user", "metadata about the requested page. @variables: acadTtForm - data of", "context) @login_required def add_timetable(request): \"\"\" acad-admin can upload the time", "range(1, 9): # sem = MinimumCredits.objects.all().filter(semester=i).first() # sem.credits = sem_cred[i+1]", "= HoldsDesignation.objects.all().filter(designation = desig_id).first() # print (temp) # print (current_user)", "user_details = ExtraInfo.objects.all().filter(user=current_user).first() # desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp", "render(request, \"ais/ais.html\", context) @login_required def add_curriculum(request): \"\"\" This function is", "registered') data.append(z) for i in registered_students: z = [] z.append(m)", "# for des in hDes: # if des.designation == s", "== \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except Exception as e:", "- Branch from form request_programme - Programme from form request_sem", "request_programme = \"\" request_sem = \"\" #for checking if the", "as e: examTtForm = \"\" acadTtForm = \"\" calendar =", "to add an entry to the academic calendar to be", ":['3','2'] } if request.method == 'POST': i=0 new_curr=[] while True:", ": hod_flag, 'account_flag' : account_flag } return context @login_required def", "- check for designation acadadmin - designation for Acadadmin final_user", "programme - the programme the student is enrolled in #", "form.REQUEST course_id - course_id from database credits - credits from", "= 4 num = 1 for i in ans: sheet.write_number('A'+str(k),num,normaltext)", "= obj.hod_status account_flag = obj.account_status except Exception as e: examTtForm", "- formatting variable of title text dep - temporary variables", "@csrf_exempt def deleteSenator(request, pk): # \"\"\" # to remove a", "update the additional courses # @param: # request - contains", "= request.POST['delete'] # t = Meeting.objects.get(id=data) # t.delete() return HttpResponseRedirect('/aims/')", "- Programme from form request_sem - Semester from form curriculum", "sheet.write_string('D3',\"Discipline\",subtitle) sheet.write_string('E3','Signature',subtitle) sheet.set_column('A:A',20) sheet.set_column('B:B',20) sheet.set_column('C:C',60) sheet.set_column('D:D',15) sheet.set_column('E:E',30) k = 4", "hDes = HoldsDesignation.objects.filter(user = student.user) # designation = [] #", "object of the student with that rollno # s -", "request_branch = \"\" request_programme = \"\" if request_batch == \"\"", "- hall no of where the student stays # room", "desig_id).first() #print (temp) # print (current_user) # acadadmin = temp.working", "request.POST.get('semester_no') batch_id=request.POST.get('batch_branch') batch = Batch.objects.filter(id = batch_id).first() obj = InitialRegistration.objects.filter(student_id__batch_id=batch_id,", "def curriculum(request): \"\"\" This function is used to see curriculum", "acadmic admin to update the additional courses # @param: #", "int(now.year) batch = year-1 curriculum = Curriculum.objects.all().select_related().filter(batch = batch).filter(programme =", "= None #Curriculum.objects.all() else: if int(request_sem) == 0: curriculum =", "final designation of request user \"\"\" try: current_user = get_object_or_404(User,", "# 'grades': grades, # 'tab_id' :\"2\" # } # return", "course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all() exam_t = Exam_timetable.objects.all() pgstudent", "unregistered_students = set() for stu in obj: registered_students.add(stu.student_id) students =", "8] else: course_list_2 = [1, 3, 5, 7] # examTtForm", "extraInfo.id, # 'programme': student.programme, # 'branch': extraInfo.department.name # } #", "obj in assis_stat: assistant_flag = obj.student_status hod_flag = obj.hod_status account_flag", "assistant_list_length = len(assistant_list.filter(acad_approval = False)) assis_stat = Assistantship_status.objects.all() for obj", "HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Assistant Professor\")) f2 = HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Professor\")) f3", "# course - get the course details # \"\"\" #", "the form required to add exam timetable exam_t - all", "request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum = None", "return JsonResponse(data) # @csrf_exempt def delete_basic_profile(request, pk): # \"\"\" #", "[1, 3, 5, 7] else: return [2, 4, 6, 8]", "\"\"\" This function is used to edit curriculum in database", "= Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).order_by('sem') else: curriculum =", "after pre-registration @param: request - contains metadata about the requested", "batch = Batch.objects.all().filter(name = programme_name, discipline__acronym = dept, year =", "particular student field # @variables: # s - the designation", "# student - the student object of the new senator", "Course.objects.all() courses_list = Courses.objects.all() course_type = Constants.COURSE_TYPE timetable = Timetable.objects.all()", "batch).filter(programme= programme).filter(sem = sem) # print(curriculum_courses) # courses = Course.objects.all()", "- course_id from database credits - credits from form.REQUEST optional", "temporary array to add data to variable data k -temporary", "dele - data being deleted from database \"\"\" if user_check(request):", "# return render(request, \"ais/ais.html\", {}) def deleteMinute(request): # \"\"\" #", "# des.delete() # data = { # 'id': pk, #", "\"\" and request_branch == \"\" and request_programme==\"\" and request_sem==\"\": curriculum", "course): # print(p.course_id) # p.delete() # else: # return HttpResponse(\"Unable", "Student.objects.filter(batch_id = batch_id) for stu in students: if stu not", "sheet @variables: now - current datetime month - current month", "for the academic calendar event. to_date - The ending date", "or not # course - get the course details #", "@variables: current_user - father's name of the student user_details -", "# stu = arr[0] # if Student.objects.get(id=stu): # s =", "Grades.objects.filter(curriculum_id=curr_course) # context= { # 'grades': grades, # 'tab_id' :\"2\"", "name = request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme =", "break i+=1 return render(request, \"ais/ais.html\", context) # # ---------------------senator------------------ #", "father = request.POST.get('father') # mother = request.POST.get('mother') # add =", "# return JsonResponse(data) # else: # father = request.POST.get('father') #", "# name - the name of the student # roll", "the student will become # convenor or coconvenor # hDes", "as e: id=\"\" programme=\"\" batch=\"\" branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\"", "'tab_id' :['3','1'] } return render(request, \"ais/ais.html\", context) else: return render(request,", "procedures_context = acad_proced_global_context() try: examTtForm = ExamTimetableForm() acadTtForm = AcademicTimetableForm()", "MinuteForm(request.POST, request.FILES) # if form.is_valid(): # form.save() # return HttpResponse('sucess')", "== 'POST': try: request_batch = request.POST['batch'] request_branch = request.POST['branch'] request_programme", "# data = { # 'name': extraInfo.user.username, # 'rollno_convenor': extraInfo.id,", "and request.FILES: profiles=request.FILES['profiles'] excel = xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in", "contains metadata about the requested page @variables: batch - gets", "response['Content-Disposition'] = st return response @login_required def add_new_profile (request): \"\"\"", "request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"] course_code=request.POST[\"course_code\"]", "# if request.method == \"POST\": # st = request.POST['delete'] #", "title text dep - temporary variables z - temporary variables", "\"\" courses = \"\" course_type = \"\" timetable = \"\"", "- get hold_desig object of student currs - get curriculum", "sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data =", "# sem=request.POST['sem'] # curriculum_courses = Curriculum.objects.filter(branch = branch).filter(batch = batch).filter(programme=", "file having data excel - excel file sheet - sheet", "request - contains metadata about the requested page. @variables: request_batch", "\"\"\" acad-admin can upload the exam timtable of the ongoing", "optional from form.REQUEST course_type - course_type from form.REQUEST ins -", "desc=\"\" return render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) #Generate", "credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first() entry.programme=programme entry.batch=batch entry.branch=branch entry.sem=sem entry.course_code=course_code", "# s.delete() # e.delete() # u.delete() # return JsonResponse(data)# #########################################################", "user_details - gets the details of the required user. #", "student holds_desig - get hold_desig object of student currs -", "from form.REQUEST optional - optional from form.REQUEST course_type - course_type", "contains senator # student - the list students that is", "request_branch == \"\" and request_programme==\"\": curriculum = None #Curriculum.objects.all() else:", "programme) courses = Course.objects.all() course_type = Constants.COURSE_TYPE context= { 'courses':", "{ 'courses': courses, 'course_type': course_type, 'curriculum': curriculum, 'tab_id' :['3','2'] }", "@variables: senates - the extraInfo objects that holds the designation", "timetable from database \"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') timetable =", "contains metadata about the requested page. @variables: acadTtForm - data", "add_timetable(request): \"\"\" acad-admin can upload the time table(any type of)", "= mothers_name, cpi = 0, category = category, hall_no =", "= 4 num = 1 for i in data: sheet.write_number('A'+str(k),num,normaltext)", "courses = [] for course_slot in course_slots: courses += course_slot.courses.all()", "to edit curriculum in database It checkes the authentication of", "checkes the authentication of the user and also fetches the", "metadata about the requested page. @variables: examTtForm - data of", "of the user and also fetches the available data from", "= (\"Pre-registeration : \"+ batch.name + str(\" \") + batch.discipline.acronym", "contains metadata about the requested page @variables: acadTtForm - the", "= 1 for i in unregistered_students: z = [] z.append(m)", "c==0: ins=Curriculum_Instructor( curriculum_id=flot, instructor_id=inst, chief_inst=True, ) new_curr_inst.append(ins) else: ins=Curriculum_Instructor( curriculum_id=flot,", "from xhtml2pdf import pisa from itertools import chain from django.contrib.auth.models", "[int(i) for i in from_date] from_date = datetime.datetime(*from_date).date() to_date =", "extraInfo objects that holds the designation as a dean student", "the phone number of the student # \"\"\" if request.method", "user=user, title=title, sex=sex, date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1", "int(now.month) if month >= 7 and month <= 12: return", "to_date = datetime.datetime(*to_date).date() except Exception as e: from_date=\"\" to_date=\"\" desc=\"\"", "# db.id = roll # db.batch = batch # db.programme", "# if i.course_id not in choices: # i.acad_selection = False", "in post request t - Object of time table to", "''' # # view to add attendance data to database", "objects in the Student class Convenor - the extraInfo objects", "= Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem=sem).order_by('course_code') faculty_list = get_faculty_list()", "# \"\"\" # acadmic admin to update the additional courses", "AssistantshipClaim,Assistantship_status from applications.globals.models import (Designation, ExtraInfo, HoldsDesignation, DepartmentInfo) from .forms", "# request - contains metadata about the requested page. #", "from database to send to template @param: request - contains", "'align': 'center', 'valign': 'vcenter'}) subtitle = book.add_format({'bold': True, 'font_size': 15,", "context) @login_required def delete_timetable(request): \"\"\" acad-admin can delete the outdated", "curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme= request_programme).filter(sem= request_sem) #", "from django.shortcuts import get_object_or_404, render from django.template.loader import get_template from", "gets the details of the required user. # desig_id -", "from the database and the update it. # \"\"\" if", "xlsx k -temporary array to add data to formatted array/variable", "contains metadata about the requested page # pk - the", "request.POST['programme'] except Exception as e: request_batch = \"\" request_branch =", "render_to_string from django.contrib.auth.decorators import login_required from applications.academic_procedures.models import MinimumCredits, Register,", "like username,password, name, # rollno, etc of a student #", "title_text = (\"Pre-registeration : \"+ batch.name + str(\" \") +", "timetable - all the academic timetable objects calendar - all", "credits=request.POST[\"credits\"] if request.POST['optional'] == \"on\": optional=True else: optional=False course_type=request.POST[\"course_type\"] except", "'align': 'center', 'valign': 'vcenter'}) sheet = book.add_worksheet() title_text = ((str(course.name)+\"", "= { # 'rollno': pk, # } # s.delete() #", "the advance information of the student # @param: # request", "for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value) sex=str(sheet.cell(i,4).value) if", "branch=\"\" sem=\"\" course_code=\"\" course_name=\"\" course_id=\"\" credits=\"\" optional=\"\" course_type=\"\" pass entry=Curriculum.objects.all().select_related().filter(curriculum_id=id).first()", "if request.POST['option'] == '1': new_curriculum=[] for i in curriculum: ins=Curriculum(", "= sem[year-int(request_batch)] sem+=1 curriculum = Curriculum.objects.select_related().filter(branch = request_branch).filter(batch = request_batch).filter(programme=", "# to set minimum credit for a current semester that", "hall_no = hall_no, specialization = specialization, curr_semester_no=sem, ) desig =", "branch from form.REQUEST sem - semester from form.REQUEST course_code -", "programme the student is enrolled in # ph - the", "request_programme==\"\" and request_sem==\"\": curriculum = None #Curriculum.objects.all() else: if int(request_sem)", "= set() for stu in obj: registered_students.add(stu.student_id) students = Student.objects.filter(batch_id", "a current semester that a student must take # @param:", "= \"\" pass context = { 'acadTtForm': acadTtForm, 'examTtForm': examTtForm,", "is used to decide curriculum for new batch. It checkes", "\"\"\" to float courses for the next sem and store", "no in excel file roll_no - details of student from", "batch # db.programme = programme # st.phone_no = ph #", "to check if the student is available # mother -", "the # information that the particular student is a convenor/coconvenor", "a senator # hDes - the holdDesignation object that stores", "user_check(request): return HttpResponseRedirect('/academic-procedures/') context= { 'tab_id' :['2','1'] } if request.method", "== 'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value)", "logged in and must be acadadmin @param: request - contains", "variable of title text dep - temporary variables z -", "Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation = desig_id).first() # print (temp) #", "delete it or not # course - get the course", "'curriculum' : curriculum, # 'tab_id' :['3','1'] # } courses =", "# hDes.designation = s # hDes.save() # student = Student.objects.get(id=extraInfo)", "batch = request.POST.get('batch') # ph = request.POST.get('phoneno') # if not", "- the extraInfo objects that holds the designation as a", "st return response @login_required def add_new_profile (request): \"\"\" To add", "take # @param: # request - contains metadata about the", "holding the senator designation # student - the student object", "- contains metadata about the requested page. @variables: acadTtForm -", "procedures_context['result_year'], 'batch_grade_data' : procedures_context['batch_grade_data'], 'batch_branch_data' : procedures_context['batch_branch_data'], 'assistant_flag' : assistant_flag,", "student # \"\"\" e = get_object_or_404(ExtraInfo, id=pk) # user =", "senator # data - data of the student to be", "of thsi semester courses next_sem_courses - the data of next", "add - student's address # cpi - student's cpi #", "\"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request): \"\"\"", "= list(chain(f1,f2,f3)) faculty_list = [] for i in faculty: faculty_list.append(i)", "batch).filter(programme = programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] }", "= request.POST.get('name') # roll = ExtraInfo.objects.get(id=request.POST.get('rollno')) # programme = request.POST.get('programme')", "the current user # desig_id - checking the designation of", "contains metadata about the requested page. @variables: f1,f2,f3 - temporary", "= student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else: #", "} return render(request, \"ais/ais.html\", context) @login_required def add_timetable(request): \"\"\" acad-admin", "= programme # st.phone_no = ph # db.save() # st.save()", "@variables: dele - data being deleted from database \"\"\" if", "k.append(i.student_id.id.id) k.append(i.student_id.id.user.first_name) k.append(i.student_id.id.user.last_name) k.append(i.student_id.id.department) ans.append(k) ans.sort() output = BytesIO() book", "details of student from file mothers_name - details of student", "registered_students: unregistered_students.add(stu) data = [] m = 1 for i", "- data of the student to be displayed in teh", "Designation.objects.get(name='Senator') # hDes = HoldsDesignation() # hDes.user = extraInfo.user #", "Bytes object to write to xlsx file book - workbook", "@login_required def update_calendar(request): \"\"\" to update an entry to the", "output st - temporary variables for final output \"\"\" if", "all the departments in the college attendance - all the", "discipline__acronym = dept, year = batch_year).first() user = User.objects.create_user( username=roll_no,", "@variables: f1,f2,f3 - temporary varibles faculty - details of faculty", "programme) context= { 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request,", "request.method == 'POST' and request.FILES: examTtForm = ExamTimetableForm(request.POST, request.FILES) if", "key of that particular student field # @variables: # s", "where the student will become # convenor or coconvenor #", "\"Associate Professor\")) except Exception as e: f1=f2=f3=\"\" pass faculty =", "= Curriculum.objects.all().select_related().filter(sem__in=course_list).filter(floated=True) next_sem_courses = Curriculum.objects.all().select_related().filter(sem__in=course_list_2).filter(floated=True) courses = Course.objects.all() courses_list =", "- temporary variables for final output \"\"\" if user_check(request): return", "---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\" # to add", "# 'branch': extraInfo.department.name # } # return HttpResponseRedirect('/aims/') # #", "This function is used to decide curriculum for new batch.", "must be logged in and must be acadadmin @param: request", "courses = Course.objects.all() # for i in courses: # if", "the academic calendar event. c = object to save new", "DepartmentInfo) from .forms import AcademicTimetableForm, ExamTimetableForm, MinuteForm from .models import", "courses: reg=course_registration( course_id = c, semester_id=sem_id, student_id=stud_data ) new_reg.append(reg) course_registration.objects.bulk_create(new_reg)", "xlrd.open_workbook(file_contents=profiles.read()) sheet=excel.sheet_by_index(0) for i in range(sheet.nrows): roll_no=int(sheet.cell(i,0).value) first_name=str(sheet.cell(i,1).value) last_name=str(sheet.cell(i,2).value) email=str(sheet.cell(i,3).value)", "student is enrolled in # ph - the phone number", "# else: # return HttpResponse(\"Unable to delete data\") return HttpResponse(\"Data", "to get the details of the required user. # \"\"\"", "'F': title='Ms.' else: title='Mr.' dob_tmp=sheet.cell(i,5).value dob_tmp=sheet.cell_value(rowx=i,colx=5) dob=datetime.datetime(*xlrd.xldate_as_tuple(dob_tmp,excel.datemode)) fathers_name=str(sheet.cell(i,6).value) mothers_name=str(sheet.cell(i,7).value) category=str(sheet.cell(i,8).value)", "senator(request): # \"\"\" # to add a new student senator", "semester courses courses - all the courses in curriculum course_type", "the calendar instance from the database for the previous Description.", "user = student.user) # hDes.delete() # return HttpResponseRedirect('/aims/') # else:", "# data = { # 'name': extraInfo.user.username, # 'rollno': extraInfo.id,", "# db.programme = programme # st.phone_no = ph # db.save()", "timtable of the ongoing semester. @param: request - contains metadata", "context) # # ---------------------senator------------------ # @csrf_exempt def senator(request): # \"\"\"", "{ 'curriculumm' :curriculum, 'tab_id' :['3','3'] } return render(request, \"ais/ais.html\", context)", "the database for the previous Description. \"\"\" if user_check(request): return", "file roll_no - details of student from file first_name -", "data = {} # return JsonResponse(data) # @csrf_exempt def deleteConvenor(request,", "{ 'exam': exam_t, 'timetable': timetable, 'tab_id' :['10','1'] } acadTtForm =", "render(request, \"ais/ais.html\", context) return render(request, \"ais/ais.html\", context) @login_required def delete_timetable(request):", "= HoldsDesignation.objects.select_related().filter(designation=Designation.objects.get(name = \"Associate Professor\")) except Exception as e: f1=f2=f3=\"\"", "ExtraInfo.objects.all().select_related('user','department').filter(user=current_user).first() desig_id = Designation.objects.all().filter(name='Upper Division Clerk') temp = HoldsDesignation.objects.all().select_related().filter(designation =", "procedures_context['lists'], 'date': procedures_context['date'], 'query_option1': procedures_context['query_option1'], 'query_option2': procedures_context['query_option2'], 'course_verification_date' : procedures_context['course_verification_date'],", "date_of_birth=dob, address=address, phone_no=phone_no, user_type='student', department=department, ) sem=1 stud_data = Student.objects.create(", "student user_details - the rollno of the student required to", "s: # if (str(p.course_id) == course): # print(p.course_id) # p.delete()", "semester of the student # data - tag whether to", "Course.objects.all() # course_type = Constants.COURSE_TYPE # timetable = Timetable.objects.all() #", "new user created in database einfo - new extrainfo object", "if request.method == 'POST': try: id=request.POST['id'] programme=request.POST['programme'] batch=request.POST['batch'] branch=request.POST['branch'] sem=request.POST[\"sem\"]", "@login_required def add_timetable(request): \"\"\" acad-admin can upload the time table(any", "# return JsonResponse(data)# ###################################################### # # ##########Senate meeting Minute################## #", "system year - current year batch - batch form form", "Exception as e: from_date=\"\" to_date=\"\" desc=\"\" return render(request, \"ais/ais.html\", context)", "students: if stu not in registered_students: unregistered_students.add(stu) data = []", "pk # hDes - the holdDesignation object that stores the", "return HttpResponseRedirect('/academic-procedures/') def min_cred(request): # \"\"\" # to set minimum", "- details of student from file sex - details of", "roll - the rollno of the student # batch -", "\"\"\" if user_check(request): return HttpResponseRedirect('/academic-procedures/') if request.method == \"POST\": data", "None #Curriculum.objects.all() else: sem = sem_for_generate_sheet() now = datetime.datetime.now() year", "course_type = Constants.COURSE_TYPE html = render_to_string('ais/curr_list.html',{'curriculum':curriculum,'courses':courses,'course_type':course_type},request) obj = json.dumps({'html':html}) #return", "list(chain(f1,f2,f3)) faculty_list = [] for i in faculty: faculty_list.append(i) return", "\"\" calendar = \"\" this_sem_courses = \"\" next_sem_courses = \"\"" ]
[ "' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "may obtain # a copy of the License at #", "limitations # under the License. \"\"\"Functional test cases for subject-replicator\"\"\"", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for", "subject-replicator\"\"\" import sys from subject.tests import functional from subject.tests.utils import", "distributed under the License is distributed on an \"AS IS\"", "% (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request:", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "cases for subject-replicator\"\"\" import sys from subject.tests import functional from", "obtain # a copy of the License at # #", "sys from subject.tests import functional from subject.tests.utils import execute class", "applicable law or agreed to in writing, software # distributed", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def", "Version 2.0 (the \"License\"); you may # not use this", "subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out,", "specific language governing permissions and limitations # under the License.", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test", "# under the License. \"\"\"Functional test cases for subject-replicator\"\"\" import", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "(sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional", "import sys from subject.tests import functional from subject.tests.utils import execute", "language governing permissions and limitations # under the License. \"\"\"Functional", "tests for subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928", "for subject-replicator\"\"\" import sys from subject.tests import functional from subject.tests.utils", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292", "subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd =", "--debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False) self.assertIn(", "either express or implied. See the # License for the", "under the License is distributed on an \"AS IS\" BASIS,", "# Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "for subject-replicator\"\"\" def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd", "may # not use this file except in compliance with", "governing permissions and limitations # under the License. \"\"\"Functional test", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "test cases for subject-replicator\"\"\" import sys from subject.tests import functional", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "exitcode, out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET http://az1:9292/v1/subjects/detail?is_public=None',", "you may # not use this file except in compliance", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator '", "from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\"", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "compliance with the License. You may obtain # a copy", "the Apache License, Version 2.0 (the \"License\"); you may #", "\"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test for issue:", "TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): # Test for", "err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET http://az1:9292/v1/subjects/detail?is_public=None', err )", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,))", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "See the # License for the specific language governing permissions", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "-m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode,", "az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd, raise_error=False)", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "the # License for the specific language governing permissions and", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "permissions and limitations # under the License. \"\"\"Functional test cases", "def test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests", "file except in compliance with the License. You may obtain", "= ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug' %", "for the specific language governing permissions and limitations # under", "law or agreed to in writing, software # distributed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "implied. See the # License for the specific language governing", "the License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys from", "\"\"\"Functional test cases for subject-replicator\"\"\" import sys from subject.tests import", "out, err = execute(cmd, raise_error=False) self.assertIn( 'Request: GET http://az1:9292/v1/subjects/detail?is_public=None', err", "az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err = execute(cmd,", "License. You may obtain # a copy of the License", "'compare az1:9292 az2:9292 --debug' % (sys.executable,)) exitcode, out, err =", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m subject.cmd.replicator ' 'compare", "# Unless required by applicable law or agreed to in", "and limitations # under the License. \"\"\"Functional test cases for", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys from subject.tests", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self): #", "import execute class TestGlanceReplicator(functional.FunctionalTest): \"\"\"Functional tests for subject-replicator\"\"\" def test_compare(self):", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "under the License. \"\"\"Functional test cases for subject-replicator\"\"\" import sys", "test_compare(self): # Test for issue: https://bugs.launchpad.net/glance/+bug/1598928 cmd = ('%s -m", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "cmd = ('%s -m subject.cmd.replicator ' 'compare az1:9292 az2:9292 --debug'", "from subject.tests import functional from subject.tests.utils import execute class TestGlanceReplicator(functional.FunctionalTest):", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3,", "<<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file)", "11, 27), date(2015, 11, 26), date(2016, 11, 24), date(2020, 11,", "self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False)", "ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016, 12, 30)]:", "date(2000, 11, 23), date(2012, 11, 22), date(2013, 11, 28), date(2014,", "2, 20), date(2013, 2, 18), date(2014, 2, 17), date(2015, 2,", "= '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step))", "date(1999, 5, 31), date(2000, 5, 29), date(2012, 5, 28), date(2013,", "date(2013, 1, 21), date(2014, 1, 20), date(2015, 1, 19), date(2016,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\")", "self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13'", "= date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "7, 3), self.marketholidayss) def test_labor_day(self): for dt in [ date(1997,", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016,", "2), date(2000, 4, 21), date(2010, 4, 2), date(2018, 3, 30),", "+ relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997,", "25), date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss)", "date(1900, 4, 13), date(1901, 4, 5), date(1902, 3, 28), date(1999,", "date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "LICENSE file) # Version: 0.1 (April 7, 2021) import unittest", "self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed =", "date(1999, 1, 18), date(2000, 1, 17), date(2012, 1, 16), date(2013,", "as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year in range(1900,", "5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5,", "make determining whether a # specific date is a holiday", "4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) #", "self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015,", "# Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) #", "\"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in", "5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000, 5,", "]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "a holiday as fast and flexible as possible. # #", "]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4,", "24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010,", "4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date", "# specific sets of marketmarketholidayss on the fly. It aims", "# import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self):", "for dt in [ date(1900, 4, 13), date(1901, 4, 5),", "self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [", ") def test_christmas_day(self): for year in range(1900, 2100): dt =", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24),", "test_labor_day(self): for dt in [ date(1997, 9, 1), date(1999, 9,", "self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss", "23), date(2012, 11, 22), date(2013, 11, 28), date(2014, 11, 27),", "6), date(2000, 9, 4), date(2012, 9, 3), date(2013, 9, 2),", "date(2015, 2, 16), date(2016, 2, 15), date(2020, 2, 17), ]:", "sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis", "11, 25), date(2000, 11, 23), date(2012, 11, 22), date(2013, 11,", "marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss)", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self):", "marketholidays.US() for dt in [ date(1969, 2, 22), date(1970, 2,", "31), ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016, 12,", "relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986, 1,", "self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12,", "def test_independence_day(self): for year in range(1900, 2100): dt = date(year,", "date from dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0,", "year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year,", "4), date(2012, 9, 3), date(2013, 9, 2), date(2014, 9, 1),", "file) # Version: 0.1 (April 7, 2021) import unittest from", "12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date =", "year in range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt,", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss)", "4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def", "= date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "on the fly. It aims to make determining whether a", "5, 26), date(1999, 5, 31), date(2000, 5, 29), date(2012, 5,", "self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12,", "3, 30), date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt,", "15), date(2000, 2, 21), date(2012, 2, 20), date(2013, 2, 18),", "marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969, 5, 30),", "def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [ date(1969,", "5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010,", "date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt,", "self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed =", "= True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss)", "12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss", "self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US =", "11, 23), date(2012, 11, 22), date(2013, 11, 28), date(2014, 11,", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self):", "import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"),", "for dt in [ date(1969, 2, 22), date(1970, 2, 22),", "as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017,", "19), date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss)", "marketanalysis # ---------------- # A fast, efficient Python library for", "self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed =", "date(2012, 11, 22), date(2013, 11, 28), date(2014, 11, 27), date(2015,", "import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def", "True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss)", "unittest from datetime import date from dateutil.relativedelta import relativedelta #", "5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self):", "12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)),", "# ---------------- # A fast, efficient Python library for generating", "'2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date,", "relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False", "+ relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26),", "state # specific sets of marketmarketholidayss on the fly. It", "2, 15), date(1997, 2, 17), date(1999, 2, 15), date(2000, 2,", "1, 17), date(2012, 1, 16), date(2013, 1, 21), date(2014, 1,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for", "11, 22), date(2013, 11, 28), date(2014, 11, 27), date(2015, 11,", "lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021,", "3), date(2013, 9, 2), date(2014, 9, 1), date(2015, 9, 7),", "self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4", "1), date(2015, 9, 7), date(2016, 9, 5), date(2020, 9, 7),", "13), date(1901, 4, 5), date(1902, 3, 28), date(1999, 4, 2),", "date(2013, 11, 28), date(2014, 11, 27), date(2015, 11, 26), date(2016,", "current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date,", "ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in", "21), date(2014, 1, 20), date(2015, 1, 19), date(2016, 1, 18),", "date(2014, 9, 1), date(2015, 9, 7), date(2016, 9, 5), date(2020,", "date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26), date(1999,", "for dt in [ date(1997, 11, 27), date(1999, 11, 25),", "date(1971, 2, 15), date(1997, 2, 17), date(1999, 2, 15), date(2000,", "4, 2), date(2018, 3, 30), date(2019, 4, 19), date(2020, 4,", "aims to make determining whether a # specific date is", "marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss", "is a holiday as fast and flexible as possible. #", "import unittest from datetime import date from dateutil.relativedelta import relativedelta", "https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) # Version: 0.1", "1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15),", "1, 20), date(2015, 1, 19), date(2016, 1, 18), date(2020, 1,", "self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013, 12, 31),", "1), date(1999, 9, 6), date(2000, 9, 4), date(2012, 9, 3),", "2), date(2014, 9, 1), date(2015, 9, 7), date(2016, 9, 5),", "self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for year in", "= True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss)", "future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ ==", "marketmarketholidayss on the fly. It aims to make determining whether", "specific date is a holiday as fast and flexible as", "lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4,", "for dt in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt,", "coding: utf-8 -*- # marketanalysis # ---------------- # A fast,", "+ relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt", "date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date", "date(1901, 4, 5), date(1902, 3, 28), date(1999, 4, 2), date(2000,", "4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US)", "relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss)", "in [ date(1997, 9, 1), date(1999, 9, 6), date(2000, 9,", "test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt", "2, 17), date(1999, 2, 15), date(2000, 2, 21), date(2012, 2,", "= marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss)", "self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for", "25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "21), date(2012, 2, 20), date(2013, 2, 18), date(2014, 2, 17),", "A fast, efficient Python library for generating country, province and", "relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US", "7, 2021) import unittest from datetime import date from dateutil.relativedelta", "self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for year", "for year in range(1900, 2100): dt = date(year, 1, 1)", "2, 18), date(2014, 2, 17), date(2015, 2, 16), date(2016, 2,", "27), date(2014, 5, 26), date(2015, 5, 25), date(2016, 5, 30),", "9, 1), date(2015, 9, 7), date(2016, 9, 5), date(2020, 9,", "9, 1), date(1999, 9, 6), date(2000, 9, 4), date(2012, 9,", "11, 28), date(2014, 11, 27), date(2015, 11, 26), date(2016, 11,", "3, 28), date(1999, 4, 2), date(2000, 4, 21), date(2010, 4,", "True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def", "2, 15), date(2000, 2, 21), date(2012, 2, 20), date(2013, 2,", "16), date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss)", "2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017,", "31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self):", "19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def", "marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False)", "from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss =", "relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100): dt", "= '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date))", "dt in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss)", "province and state # specific sets of marketmarketholidayss on the", "marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013, 12,", "determining whether a # specific date is a holiday as", "18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "22), date(1971, 2, 15), date(1997, 2, 17), date(1999, 2, 15),", "17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "---------------- # A fast, efficient Python library for generating country,", "2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "datetime import date from dateutil.relativedelta import relativedelta # import sys", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7,", "efficient Python library for generating country, province and state #", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [", "4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "dt in [ date(1997, 11, 27), date(1999, 11, 25), date(2000,", "1, 19), date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt,", "Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in", "22), date(2013, 11, 28), date(2014, 11, 27), date(2015, 11, 26),", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for", "date(1997, 11, 27), date(1999, 11, 25), date(2000, 11, 23), date(2012,", "generating country, province and state # specific sets of marketmarketholidayss", "= marketholidays.US() for dt in [ date(1900, 4, 13), date(1901,", "16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self):", "27), date(2015, 11, 26), date(2016, 11, 24), date(2020, 11, 26),", "date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "fast, efficient Python library for generating country, province and state", "self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5),", "self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__", "5, 27), date(2014, 5, 26), date(2015, 5, 25), date(2016, 5,", "5, 26), date(2015, 5, 25), date(2016, 5, 30), date(2020, 5,", "in range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss)", "date(2015, 1, 19), date(2016, 1, 18), date(2020, 1, 20), ]:", "31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False for", "date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "\"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for", "4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for", "15), date(1997, 2, 17), date(1999, 2, 15), date(2000, 2, 21),", "]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in", "self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100): dt =", "self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for", "whether a # specific date is a holiday as fast", "for dt in [ date(1969, 5, 30), date(1970, 5, 30),", "20), date(2013, 2, 18), date(2014, 2, 17), date(2015, 2, 16),", "self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date", "9, 3), date(2013, 9, 2), date(2014, 9, 1), date(2015, 9,", "26), date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss)", "15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for", "11, 27), date(1999, 11, 25), date(2000, 11, 23), date(2012, 11,", "It aims to make determining whether a # specific date", "date(1997, 2, 17), date(1999, 2, 15), date(2000, 2, 21), date(2012,", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents'", "5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt", "year in range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt,", "= markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1,", "dt in [ date(1986, 1, 20), date(1999, 1, 18), date(2000,", "Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year", "self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step))", "17), date(2012, 1, 16), date(2013, 1, 21), date(2014, 1, 20),", "def test_martin_luther(self): for dt in [ date(1986, 1, 20), date(1999,", "16), date(2013, 1, 21), date(2014, 1, 20), date(2015, 1, 19),", "def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4,", "self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986, 1, 20),", "4, 21), date(2010, 4, 2), date(2018, 3, 30), date(2019, 4,", "5, 31), date(2000, 5, 29), date(2012, 5, 28), date(2013, 5,", "= False for year in range(1900, 2100): dt = date(year,", "2, 17), date(2015, 2, 16), date(2016, 2, 15), date(2020, 2,", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12,", "nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012,", "self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US()", "28), date(2013, 5, 27), date(2014, 5, 26), date(2015, 5, 25),", "25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1),", "5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010,", "for year in range(1900, 2100): dt = date(year, 7, 4)", "test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed", "31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010,", "'2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021,", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7,", "26), date(2015, 5, 25), date(2016, 5, 30), date(2020, 5, 25),", "9, 2), date(2014, 9, 1), date(2015, 9, 7), date(2016, 9,", "30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13'", "24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23),", "relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss)", "date(2000, 9, 4), date(2012, 9, 3), date(2013, 9, 2), date(2014,", "20), date(1999, 1, 18), date(2000, 1, 17), date(2012, 1, 16),", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss =", "= '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step))", "12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020,", "self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self):", "26), date(1999, 5, 31), date(2000, 5, 29), date(2012, 5, 28),", "self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1,", "import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US()", "Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE file) # Version:", "date(2010, 4, 2), date(2018, 3, 30), date(2019, 4, 19), date(2020,", "27), date(1999, 11, 25), date(2000, 11, 23), date(2012, 11, 22),", "# Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT", "in [date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt,", "date(2014, 2, 17), date(2015, 2, 16), date(2016, 2, 15), date(2020,", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900,", "relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997, 11,", "date(2012, 9, 3), date(2013, 9, 2), date(2014, 9, 1), date(2015,", "date(1999, 4, 2), date(2000, 4, 21), date(2010, 4, 2), date(2018,", "future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4,", "1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "from dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/')", "2, 22), date(1971, 2, 15), date(1997, 2, 17), date(1999, 2,", "date(2015, 9, 7), date(2016, 9, 5), date(2020, 9, 7), ]:", "marketholidayss_US = marketholidays.US() for dt in [ date(1900, 4, 13),", "# A fast, efficient Python library for generating country, province", "Version: 0.1 (April 7, 2021) import unittest from datetime import", "test_thanksgiving_day(self): for dt in [ date(1997, 11, 27), date(1999, 11,", "def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year", "self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt in [", "self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step = 10", "date(1997, 9, 1), date(1999, 9, 6), date(2000, 9, 4), date(2012,", "26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28),", "17), date(1999, 2, 15), date(2000, 2, 21), date(2012, 2, 20),", "test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12,", "de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for", "test_memorial_day(self): for dt in [ date(1969, 5, 30), date(1970, 5,", "[ date(1969, 2, 22), date(1970, 2, 22), date(1971, 2, 15),", "the fly. It aims to make determining whether a #", "# # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License:", "date(2013, 5, 27), date(2014, 5, 26), date(2015, 5, 25), date(2016,", "4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step", "9, 7), date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt,", "self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26),", "True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed", "2021) import unittest from datetime import date from dateutil.relativedelta import", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010,", "self.marketholidayss) def test_labor_day(self): for dt in [ date(1997, 9, 1),", "7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas", "test_christmas_day(self): for year in range(1900, 2100): dt = date(year, 12,", "date(2000, 5, 29), date(2012, 5, 28), date(2013, 5, 27), date(2014,", "= marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for dt in [date(2013,", "self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step))", "<reponame>OmoMicheal/marketanalysis<gh_stars>1-10 # -*- coding: utf-8 -*- # marketanalysis # ----------------", "12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ == \"__main__\": #", "5, 28), date(2013, 5, 27), date(2014, 5, 26), date(2015, 5,", "marketanalysis import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def", "date(2000, 2, 21), date(2012, 2, 20), date(2013, 2, 18), date(2014,", "License: MIT (see LICENSE file) # Version: 0.1 (April 7,", "21), date(2010, 4, 2), date(2018, 3, 30), date(2019, 4, 19),", "def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31), ky_marketholidayss) for", "self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed =", "2, 21), date(2012, 2, 20), date(2013, 2, 18), date(2014, 2,", "[ date(1997, 11, 27), date(1999, 11, 25), date(2000, 11, 23),", "self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24),", "nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12,", "range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year", "and flexible as possible. # # Author: MichealOmojola <<EMAIL>> #", "def test_memorial_day(self): for dt in [ date(1969, 5, 30), date(1970,", "(see LICENSE file) # Version: 0.1 (April 7, 2021) import", "Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see", "self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self):", "self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss)", "Python library for generating country, province and state # specific", "test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [ date(1969, 2,", "date(1970, 2, 22), date(1971, 2, 15), date(1997, 2, 17), date(1999,", "fast and flexible as possible. # # Author: MichealOmojola <<EMAIL>>", "7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def", "9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "in [ date(1900, 4, 13), date(1901, 4, 5), date(1902, 3,", "markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2),", "date(2013, 2, 18), date(2014, 2, 17), date(2015, 2, 16), date(2016,", "11, 26), date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt,", "fly. It aims to make determining whether a # specific", "class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA()", "date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US()", "self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step", "3), self.marketholidayss) def test_labor_day(self): for dt in [ date(1997, 9,", "11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date =", "(April 7, 2021) import unittest from datetime import date from", "26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "date is a holiday as fast and flexible as possible.", "MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days # License: MIT (see LICENSE", "self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed", "5, 25), date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt,", "date(2000, 1, 17), date(2012, 1, 16), date(2013, 1, 21), date(2014,", "def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss)", "24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss =", "date(1999, 11, 25), date(2000, 11, 23), date(2012, 11, 22), date(2013,", "date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969,", "= True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss)", "+ relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self):", "18), date(2000, 1, 17), date(2012, 1, 16), date(2013, 1, 21),", "date(1969, 2, 22), date(1970, 2, 22), date(1971, 2, 15), date(1997,", "def test_thanksgiving_day(self): for dt in [ date(1997, 11, 27), date(1999,", "nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self):", "date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "for dt in [ date(1986, 1, 20), date(1999, 1, 18),", "marketholidays.US() for dt in [ date(1900, 4, 13), date(1901, 4,", "in range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss)", "self.marketholidayss) def test_thanksgiving_day(self): for dt in [ date(1997, 11, 27),", "= marketholidays.US() self.marketholidayss.observed = False for year in range(1900, 2050):", "date(1902, 3, 28), date(1999, 4, 2), date(2000, 4, 21), date(2010,", "def test_labor_day(self): for dt in [ date(1997, 9, 1), date(1999,", "1, 2), self.marketholidayss) self.marketholidayss.observed = False for year in range(1900,", "self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss)", "self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20'", "def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016,", "range(1900, 2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12,", "import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase): def setUp(self):", "test_martin_luther(self): for dt in [ date(1986, 1, 20), date(1999, 1,", "dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US()", "self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step =", "lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date =", "relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in", "2100): dt = date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "4, 5), date(1902, 3, 28), date(1999, 4, 2), date(2000, 4,", "12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = False", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt", "25), date(2000, 11, 23), date(2012, 11, 22), date(2013, 11, 28),", "+ relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed =", "12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss)", "range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020,", "test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [ date(1900, 4,", "date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed", "2100): dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "31), date(1997, 5, 26), date(1999, 5, 31), date(2000, 5, 29),", "date(2012, 5, 28), date(2013, 5, 27), date(2014, 5, 26), date(2015,", "sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import markettradingdays", "10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date,", "def test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4,", "28), date(1999, 4, 2), date(2000, 4, 21), date(2010, 4, 2),", "4, 13), date(1901, 4, 5), date(1902, 3, 28), date(1999, 4,", "= date(year, 12, 25) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "= 4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11),", "24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\",", "12, 22)), ) def test_christmas_day(self): for year in range(1900, 2100):", "1, 21), date(2014, 1, 20), date(2015, 1, 19), date(2016, 1,", "# specific date is a holiday as fast and flexible", "date(1997, 5, 26), date(1999, 5, 31), date(2000, 5, 29), date(2012,", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss)", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss)", "country, province and state # specific sets of marketmarketholidayss on", "18), date(2014, 2, 17), date(2015, 2, 16), date(2016, 2, 15),", "2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss)", "2), date(2018, 3, 30), date(2019, 4, 19), date(2020, 4, 10),", "date(2018, 3, 30), date(2019, 4, 19), date(2020, 4, 10), ]:", "date(1999, 9, 6), date(2000, 9, 4), date(2012, 9, 3), date(2013,", "nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27),", "for dt in [ date(1997, 9, 1), date(1999, 9, 6),", "10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt", "7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True", "MIT (see LICENSE file) # Version: 0.1 (April 7, 2021)", "= True def test_new_years_eve(self): ky_marketholidayss = marketholidays.US() self.assertNotIn(date(2012, 12, 31),", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss", "de_marketholidayss = marketholidays.US() for dt in [ date(1969, 2, 22),", "[ date(1986, 1, 20), date(1999, 1, 18), date(2000, 1, 17),", "self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt,", "self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ == \"__main__\":", "date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31), date(2000,", "date(2014, 5, 26), date(2015, 5, 25), date(2016, 5, 30), date(2020,", "7), date(2016, 9, 5), date(2020, 9, 7), ]: self.assertIn(dt, self.marketholidayss)", "utf-8 -*- # marketanalysis # ---------------- # A fast, efficient", "self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7,", "= marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31),", "12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True", "'2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021,", "import date from dateutil.relativedelta import relativedelta # import sys #", "date(1986, 1, 20), date(1999, 1, 18), date(2000, 1, 17), date(2012,", "1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16),", "7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for", "date(2012, 1, 16), date(2013, 1, 21), date(2014, 1, 20), date(2015,", "2), self.marketholidayss) self.marketholidayss.observed = False for year in range(1900, 2100):", "date(1969, 5, 30), date(1970, 5, 30), date(1971, 5, 31), date(1997,", "date(2015, 11, 26), date(2016, 11, 24), date(2020, 11, 26), ]:", "TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def", "1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss)", "test_christmas_eve(self): as_marketholidayss = marketholidays.US() self.marketholidayss.observed = False for year in", "for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) #", "(Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year in", "4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def", "relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss =", "date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss)", "self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31),", "marketholidays.US() self.marketholidayss.observed = False for year in range(1900, 2050): self.assertNotIn(date(year,", "self.marketholidayss.observed = False for year in range(1900, 2050): self.assertNotIn(date(year, 12,", "20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12,", "= marketholidays.US() for dt in [ date(1969, 2, 22), date(1970,", "1, 20), date(1999, 1, 18), date(2000, 1, 17), date(2012, 1,", "[ date(1900, 4, 13), date(1901, 4, 5), date(1902, 3, 28),", "1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt +", "def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt in [ date(1900,", "'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import markettradingdays class", "self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def test_day_after_christmas(self):", "in range(1900, 2100): dt = date(year, 1, 1) self.assertIn(dt, self.marketholidayss)", "29), date(2012, 5, 28), date(2013, 5, 27), date(2014, 5, 26),", "from datetime import date from dateutil.relativedelta import relativedelta # import", "date(2012, 2, 20), date(2013, 2, 18), date(2014, 2, 17), date(2015,", "as fast and flexible as possible. # # Author: MichealOmojola", "1, 16), date(2013, 1, 21), date(2014, 1, 20), date(2015, 1,", "markettradingdays class TestUS(unittest.TestCase): def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss =", "current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date,", "marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed", "range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24),", "= 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18),", "self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3), self.marketholidayss) self.marketholidayss.observed", "False for year in range(1900, 2100): dt = date(year, 1,", "11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "to make determining whether a # specific date is a", "self.marketholidayss) self.marketholidayss.observed = False for year in range(1900, 2100): dt", "date(2016, 1, 18), date(2020, 1, 20), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "self.marketholidayss.observed = True self.assertIn(date(2010, 12, 31), self.marketholidayss) self.assertIn(date(2017, 1, 2),", "a # specific date is a holiday as fast and", "in [ date(1969, 5, 30), date(1970, 5, 30), date(1971, 5,", "18), self.markettradingdayss.BtwDates(current_date, future_date)) # if __name__ == \"__main__\": # unittest.main()", "self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.BtwDates(current_date, future_date))", "+ relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5), self.marketholidayss) self.assertNotIn(date(2020, 7, 3),", "self.marketholidayss) def test_washingtons_birthday(self): de_marketholidayss = marketholidays.US() for dt in [", "self.marketholidayss) self.assertNotIn(date(2016, 12, 26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12,", "as_marketholidayss.get_list(date(2017, 12, 22)), ) def test_christmas_day(self): for year in range(1900,", "from marketanalysis import marketholidays from marketanalysis import markettradingdays class TestUS(unittest.TestCase):", "+ relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self): for dt in [ date(1986,", "-*- coding: utf-8 -*- # marketanalysis # ---------------- # A", "possible. # # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days #", "and state # specific sets of marketmarketholidayss on the fly.", "= False for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24),", "dt in [ date(1997, 9, 1), date(1999, 9, 6), date(2000,", "12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def test_new_years_eve(self): ky_marketholidayss =", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_thanksgiving_day(self): for dt in [", "date(year, 1, 1) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "23), as_marketholidayss) self.assertNotIn( \"Christmas Eve (Observed)\", as_marketholidayss.get_list(date(2017, 12, 22)), )", "self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self): current_date = '2021-04-13'", "True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12, 26), self.marketholidayss) def", "in [ date(1969, 2, 22), date(1970, 2, 22), date(1971, 2,", "# License: MIT (see LICENSE file) # Version: 0.1 (April", "test_independence_day(self): for year in range(1900, 2100): dt = date(year, 7,", "library for generating country, province and state # specific sets", "2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date, lookback_step)) def test_BtwDates(self):", "30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "30), date(1971, 5, 31), date(1997, 5, 26), date(1999, 5, 31),", "22)), ) def test_christmas_day(self): for year in range(1900, 2100): dt", "1, 18), date(2000, 1, 17), date(2012, 1, 16), date(2013, 1,", "self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_martin_luther(self):", "7, 3), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss)", "5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "2, 15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt +", "date(2014, 11, 27), date(2015, 11, 26), date(2016, 11, 24), date(2020,", "[date(2013, 12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss)", "test_prevDays(self): current_date = '2021-04-13' lookback_step = 4 self.assertIn(date(2021, 4, 9),", "lookback_step)) def test_BtwDates(self): current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021,", "# Version: 0.1 (April 7, 2021) import unittest from datetime", "self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7,", "self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date", "flexible as possible. # # Author: MichealOmojola <<EMAIL>> # Website:", "15), date(2020, 2, 17), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 12, 24), self.marketholidayss) self.assertNotIn(date(2016, 12,", "self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12, 28), nc_marketholidayss)", "dt = date(year, 7, 4) self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "9, 4), date(2012, 9, 3), date(2013, 9, 2), date(2014, 9,", "5), date(1902, 3, 28), date(1999, 4, 2), date(2000, 4, 21),", "dt in [ date(1969, 5, 30), date(1970, 5, 30), date(1971,", "31), date(2000, 5, 29), date(2012, 5, 28), date(2013, 5, 27),", "[ date(1969, 5, 30), date(1970, 5, 30), date(1971, 5, 31),", "# self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016, 12, 23), as_marketholidayss) self.assertNotIn(", "26), self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016,", "self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def test_good_friday(self): marketholidayss_US = marketholidays.US() for dt", "+ relativedelta(days=+1), self.marketholidayss) def test_independence_day(self): for year in range(1900, 2100):", "22), date(1970, 2, 22), date(1971, 2, 15), date(1997, 2, 17),", "current_date = '2021-04-13' future_date = '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date,", "ky_marketholidayss) def test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021,", "def test_future_list(self): current_date = '2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4,", "20), date(2015, 1, 19), date(2016, 1, 18), date(2020, 1, 20),", "2, 22), date(1970, 2, 22), date(1971, 2, 15), date(1997, 2,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) def test_christmas_eve(self): as_marketholidayss", "12, 31), ky_marketholidayss) for dt in [date(2013, 12, 31), date(2016,", "specific sets of marketmarketholidayss on the fly. It aims to", "30), date(1970, 5, 30), date(1971, 5, 31), date(1997, 5, 26),", "28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True def", "self.marketholidayss.observed = False for year in range(1900, 2100): dt =", "date(2016, 11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt", "12, 28), nc_marketholidayss) self.assertNotIn(date(2016, 12, 27), nc_marketholidayss) nc_marketholidayss.observed = True", "-*- # marketanalysis # ---------------- # A fast, efficient Python", "self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017, 1, 2), self.marketholidayss) self.marketholidayss.observed =", "dateutil.relativedelta import relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from", "# -*- coding: utf-8 -*- # marketanalysis # ---------------- #", "dt in [ date(1969, 2, 22), date(1970, 2, 22), date(1971,", "date(2000, 4, 21), date(2010, 4, 2), date(2018, 3, 30), date(2019,", "9, 7), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt", "date(2013, 9, 2), date(2014, 9, 1), date(2015, 9, 7), date(2016,", "date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss) self.assertIn(dt, marketholidayss_US) def test_memorial_day(self):", "self.marketholidayss.observed = True self.assertIn(date(2010, 7, 5), self.marketholidayss) self.assertIn(date(2020, 7, 3),", "self.marketholidayss) self.marketholidayss.observed = True self.assertIn(date(2010, 12, 24), self.marketholidayss) self.assertIn(date(2016, 12,", "self.assertIn(dt, marketholidayss_US) def test_memorial_day(self): for dt in [ date(1969, 5,", "4 self.assertIn(date(2021, 4, 9), self.markettradingdayss.prevDays(current_date, lookback_step)) self.assertNotIn(date(2021, 4, 11), self.markettradingdayss.prevDays(current_date,", "for generating country, province and state # specific sets of", "date(2014, 1, 20), date(2015, 1, 19), date(2016, 1, 18), date(2020,", "for year in range(1900, 2100): dt = date(year, 12, 25)", "self.marketholidayss) self.assertIn(date(2020, 7, 3), self.marketholidayss) def test_labor_day(self): for dt in", "of marketmarketholidayss on the fly. It aims to make determining", "def setUp(self): self.marketholidayss = marketholidays.USA(observed=False) self.markettradingdayss = markettradingdays.USA() def test_new_years(self):", "self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertIn(dt, de_marketholidayss) self.assertEqual(marketholidays.US().get(\"2015-02-16\"), \"Presidents' Day\") def", "relativedelta # import sys # sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import", "date(1999, 2, 15), date(2000, 2, 21), date(2012, 2, 20), date(2013,", "+ relativedelta(days=-1), self.marketholidayss) self.assertNotIn(dt + relativedelta(days=+1), self.marketholidayss) self.assertNotIn(date(2010, 7, 5),", "date(2015, 5, 25), date(2016, 5, 30), date(2020, 5, 25), ]:", "# marketanalysis # ---------------- # A fast, efficient Python library", "lookup_step)) self.assertNotIn(date(2021, 4, 18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date =", "year in range(1900, 2100): dt = date(year, 7, 4) self.assertIn(dt,", "in [ date(1997, 11, 27), date(1999, 11, 25), date(2000, 11,", "9, 6), date(2000, 9, 4), date(2012, 9, 3), date(2013, 9,", "self.markettradingdayss = markettradingdays.USA() def test_new_years(self): self.assertNotIn(date(2010, 12, 31), self.marketholidayss) self.assertNotIn(date(2017,", "holiday as fast and flexible as possible. # # Author:", "0.1 (April 7, 2021) import unittest from datetime import date", "# sys.path.insert(0, 'C:/Users/momojola/projects/marketanalysis/marketanalysis/') from marketanalysis import marketholidays from marketanalysis import", "in [ date(1986, 1, 20), date(1999, 1, 18), date(2000, 1,", "def test_christmas_day(self): for year in range(1900, 2100): dt = date(year,", "2, 16), date(2016, 2, 15), date(2020, 2, 17), ]: self.assertIn(dt,", "self.assertNotIn(date(year, 12, 24), self.marketholidayss) # self.assertIn(date(year, 12, 24), as_marketholidayss) self.assertNotIn(date(2016,", "False for year in range(1900, 2050): self.assertNotIn(date(year, 12, 24), self.marketholidayss)", "'2021-04-13' lookup_step = 10 self.assertIn(date(2021, 4, 16), self.markettradingdayss.future_list(current_date, lookup_step)) self.assertNotIn(date(2021,", "18), self.markettradingdayss.future_list(current_date, lookup_step)) def test_prevDays(self): current_date = '2021-04-13' lookback_step =", "5, 30), date(1970, 5, 30), date(1971, 5, 31), date(1997, 5,", "24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt + relativedelta(days=-1),", "dt in [ date(1900, 4, 13), date(1901, 4, 5), date(1902,", "12, 31), date(2016, 12, 30)]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt, ky_marketholidayss) def", "= '2021-04-20' self.assertIn(date(2021, 4, 15), self.markettradingdayss.BtwDates(current_date, future_date)) self.assertNotIn(date(2021, 4, 18),", "11, 24), date(2020, 11, 26), ]: self.assertNotIn(dt, self.marketholidayss) self.assertNotIn(dt +", "date(2016, 5, 30), date(2020, 5, 25), ]: self.assertIn(dt, self.marketholidayss) self.assertNotIn(dt", "17), date(2015, 2, 16), date(2016, 2, 15), date(2020, 2, 17),", "sets of marketmarketholidayss on the fly. It aims to make", "[ date(1997, 9, 1), date(1999, 9, 6), date(2000, 9, 4),", "28), date(2014, 11, 27), date(2015, 11, 26), date(2016, 11, 24),", "12, 26), self.marketholidayss) def test_day_after_christmas(self): nc_marketholidayss = marketholidays.US(observed=False) self.assertNotIn(date(2015, 12,", "5, 29), date(2012, 5, 28), date(2013, 5, 27), date(2014, 5,", "30), date(2019, 4, 19), date(2020, 4, 10), ]: self.assertIn(dt, self.marketholidayss)", "as possible. # # Author: MichealOmojola <<EMAIL>> # Website: https://github.com/OmoMicheal/trading_days" ]
[ "d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg',", "catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg',", "package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib', 'rospkg'] )", "distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup(", "<reponame>jungleni/ros_code_reading #!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import", "generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'],", "generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib',", "from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'},", "setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'':", "import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'],", "#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup", "from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d =", "python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d", "import generate_distutils_setup d = generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto',", "= generate_distutils_setup( packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag',", "'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib', 'rospkg'] ) setup(**d)", "packages=['rosmsg'], package_dir={'': 'src'}, scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'], requires=['genmsg', 'rosbag', 'roslib', 'rospkg']" ]
[ "result.append(iter.value) iter = self.next_iter(iter) if not iter: break return result", "True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break return", "self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1])", "iter.next else: return iter def tolist(self): result = [] iter", "None def insert(self, value): self.list = Node(value, self.list) def start_iter(self):", "############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing", "= None def insert(self, value): self.list = Node(value, self.list) def", "Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests", "= self.next_iter(iter) if not iter: break return result def run(self,", "Additional modules ############################################################################### # Linked_list Class ############################################################################### class Node: def", "= Node(value, self.list) def start_iter(self): return self.list def next_iter(self, iter):", "d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\":", "tail class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\"", "None: return iter.next else: return iter def tolist(self): result =", "self.list = None def insert(self, value): self.list = Node(value, self.list)", "unittest import sys import os import argparse import re import", "self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if sys.argv[-1] ==", "python # linked_list.py - Linked list implementation in Python by", "by Sergey 2015 \"\"\" Linked list implementation in Python \"\"\"", "self.list) def start_iter(self): return self.list def next_iter(self, iter): if iter", "# Standard modules import unittest import sys import os import", "\"\"\" Main execution function \"\"\" if test: return ############################################################################### #", "def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ###############################################################################", "is not None: return iter.next else: return iter def tolist(self):", "random import subprocess import getpass import shutil # Additional modules", "Linked_list Class ############################################################################### class Node: def __init__(self, value, tail): self.value", "__name__ == \"__main__\": if sys.argv[-1] == \"-ut\": unittest.main(argv=[\" \"]) main()", "1]) if __name__ == \"__main__\": if sys.argv[-1] == \"-ut\": unittest.main(argv=[\"", "def start_iter(self): return self.list def next_iter(self, iter): if iter is", "iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__", "tolist(self): result = [] iter = self.start_iter() while True: result.append(iter.value)", "return ############################################################################### # Executable code ############################################################################### def main(): # Sandbox", "sys import os import argparse import re import random import", "insert(self, value): self.list = Node(value, self.list) def start_iter(self): return self.list", "self.list def next_iter(self, iter): if iter is not None: return", "Main execution function \"\"\" if test: return ############################################################################### # Executable", "not None: return iter.next else: return iter def tolist(self): result", "iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1)", "if __name__ == \"__main__\": if sys.argv[-1] == \"-ut\": unittest.main(argv=[\" \"])", "d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter =", "self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter =", "\"\"\" Linked_list class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list,", "Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic", "\".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def", "test=False): \"\"\" Main execution function \"\"\" if test: return ###############################################################################", "linked_list.py - Linked list implementation in Python by Sergey 2015", "self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if not iter:", "list implementation in Python by Sergey 2015 \"\"\" Linked list", "value): self.list = Node(value, self.list) def start_iter(self): return self.list def", "iter def tolist(self): result = [] iter = self.start_iter() while", "Standard modules import unittest import sys import os import argparse", "= tail class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self):", "\"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list = None", "[] iter = self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter)", "= Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class", "import argparse import re import random import subprocess import getpass", "function \"\"\" if test: return ############################################################################### # Executable code ###############################################################################", "Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor", "############################################################################### class Node: def __init__(self, value, tail): self.value = value", "if iter is not None: return iter.next else: return iter", "def tolist(self): result = [] iter = self.start_iter() while True:", "\"\"\" self.list = None def insert(self, value): self.list = Node(value,", "if test: return ############################################################################### # Executable code ############################################################################### def main():", "= d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ ==", "Executable code ############################################################################### def main(): # Sandbox sb = Linked_list(\"", "Sergey 2015 \"\"\" Linked list implementation in Python \"\"\" #", "argparse import re import random import subprocess import getpass import", "iter = self.next_iter(iter) if not iter: break return result def", "Python \"\"\" # Standard modules import unittest import sys import", "unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d", "<filename>unsorted/linked_list.py #!/usr/bin/env python # linked_list.py - Linked list implementation in", "def insert(self, value): self.list = Node(value, self.list) def start_iter(self): return", "import subprocess import getpass import shutil # Additional modules ###############################################################################", "value, tail): self.value = value self.next = tail class Linked_list:", "import random import subprocess import getpass import shutil # Additional", "Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list", "\"\"\" Default constructor \"\"\" self.list = None def insert(self, value):", "def run(self, test=False): \"\"\" Main execution function \"\"\" if test:", "main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### #", "Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase):", "getpass import shutil # Additional modules ############################################################################### # Linked_list Class", "= [] iter = self.start_iter() while True: result.append(iter.value) iter =", "Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class", "code ############################################################################### def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:]))", "self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if", "import re import random import subprocess import getpass import shutil", "import shutil # Additional modules ############################################################################### # Linked_list Class ###############################################################################", "None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter()", "\"\"\" # Standard modules import unittest import sys import os", "\"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\"", "# Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list", "else: return iter def tolist(self): result = [] iter =", "# Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit", "__init__(self, value, tail): self.value = value self.next = tail class", "implementation in Python by Sergey 2015 \"\"\" Linked list implementation", "basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value,", "= d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(),", "testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1)", "\"\"\" Linked list implementation in Python \"\"\" # Standard modules", "result def run(self, test=False): \"\"\" Main execution function \"\"\" if", "1) self.assertEqual(d.tolist(), [2, 1]) if __name__ == \"__main__\": if sys.argv[-1]", "if not iter: break return result def run(self, test=False): \"\"\"", "# Additional modules ############################################################################### # Linked_list Class ############################################################################### class Node:", "class Node: def __init__(self, value, tail): self.value = value self.next", "def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d =", "self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2)", "\"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2)", "d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value,", "self.next_iter(iter) if not iter: break return result def run(self, test=False):", "representation \"\"\" def __init__(self): \"\"\" Default constructor \"\"\" self.list =", "# linked_list.py - Linked list implementation in Python by Sergey", "iter): if iter is not None: return iter.next else: return", "list implementation in Python \"\"\" # Standard modules import unittest", "iter: break return result def run(self, test=False): \"\"\" Main execution", "test: return ############################################################################### # Executable code ############################################################################### def main(): #", "2015 \"\"\" Linked list implementation in Python \"\"\" # Standard", "############################################################################### # Executable code ############################################################################### def main(): # Sandbox sb", "iter is not None: return iter.next else: return iter def", "return self.list def next_iter(self, iter): if iter is not None:", "__init__(self): \"\"\" Default constructor \"\"\" self.list = None def insert(self,", "os import argparse import re import random import subprocess import", "Node: def __init__(self, value, tail): self.value = value self.next =", "\"\"\" if test: return ############################################################################### # Executable code ############################################################################### def", "sb.run() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self):", "subprocess import getpass import shutil # Additional modules ############################################################################### #", "run(self, test=False): \"\"\" Main execution function \"\"\" if test: return", "Node(value, self.list) def start_iter(self): return self.list def next_iter(self, iter): if", "import getpass import shutil # Additional modules ############################################################################### # Linked_list", "return iter def tolist(self): result = [] iter = self.start_iter()", "def __init__(self): \"\"\" Default constructor \"\"\" self.list = None def", "in Python \"\"\" # Standard modules import unittest import sys", "self.list = Node(value, self.list) def start_iter(self): return self.list def next_iter(self,", "d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2,", "re import random import subprocess import getpass import shutil #", "return result def run(self, test=False): \"\"\" Main execution function \"\"\"", "[2, 1]) if __name__ == \"__main__\": if sys.argv[-1] == \"-ut\":", "2) iter = d.next_iter(iter) self.assertEqual(iter.value, 1) self.assertEqual(d.tolist(), [2, 1]) if", "class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None) d.insert(1)", "Class ############################################################################### class Node: def __init__(self, value, tail): self.value =", "return iter.next else: return iter def tolist(self): result = []", "1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter) self.assertEqual(iter.value,", "import os import argparse import re import random import subprocess", "modules ############################################################################### # Linked_list Class ############################################################################### class Node: def __init__(self,", "#!/usr/bin/env python # linked_list.py - Linked list implementation in Python", "class Linked_list: \"\"\" Linked_list representation \"\"\" def __init__(self): \"\"\" Default", "class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\"", "while True: result.append(iter.value) iter = self.next_iter(iter) if not iter: break", "implementation in Python \"\"\" # Standard modules import unittest import", "import unittest import sys import os import argparse import re", "= self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if not", "- Linked list implementation in Python by Sergey 2015 \"\"\"", "self.next = tail class Linked_list: \"\"\" Linked_list representation \"\"\" def", "in Python by Sergey 2015 \"\"\" Linked list implementation in", "def next_iter(self, iter): if iter is not None: return iter.next", "not iter: break return result def run(self, test=False): \"\"\" Main", "# Executable code ############################################################################### def main(): # Sandbox sb =", "############################################################################### # Linked_list Class ############################################################################### class Node: def __init__(self, value,", "next_iter(self, iter): if iter is not None: return iter.next else:", "self.value = value self.next = tail class Linked_list: \"\"\" Linked_list", "############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Linked_list_class__basic_functionality(self): \"\"\"", "value self.next = tail class Linked_list: \"\"\" Linked_list representation \"\"\"", "test_Linked_list_class__basic_functionality(self): \"\"\" Linked_list class basic testing \"\"\" d = Linked_list()", "Python by Sergey 2015 \"\"\" Linked list implementation in Python", "execution function \"\"\" if test: return ############################################################################### # Executable code", "sb = Linked_list(\" \".join(sys.argv[1:])) sb.run() ############################################################################### # Unit Tests ###############################################################################", "Linked list implementation in Python by Sergey 2015 \"\"\" Linked", "= value self.next = tail class Linked_list: \"\"\" Linked_list representation", "iter = self.start_iter() while True: result.append(iter.value) iter = self.next_iter(iter) if", "import sys import os import argparse import re import random", "Default constructor \"\"\" self.list = None def insert(self, value): self.list", "############################################################################### def main(): # Sandbox sb = Linked_list(\" \".join(sys.argv[1:])) sb.run()", "d = Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value,", "shutil # Additional modules ############################################################################### # Linked_list Class ############################################################################### class", "def __init__(self, value, tail): self.value = value self.next = tail", "self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter = d.next_iter(iter)", "Linked_list class basic testing \"\"\" d = Linked_list() self.assertEqual(d.list, None)", "Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter", "1) d.insert(2) self.assertEqual(d.list.next.value, 1) iter = d.start_iter() self.assertEqual(iter.value, 2) iter", "= Linked_list() self.assertEqual(d.list, None) d.insert(1) self.assertEqual(d.list.value, 1) d.insert(2) self.assertEqual(d.list.next.value, 1)", "# Linked_list Class ############################################################################### class Node: def __init__(self, value, tail):", "start_iter(self): return self.list def next_iter(self, iter): if iter is not", "modules import unittest import sys import os import argparse import", "tail): self.value = value self.next = tail class Linked_list: \"\"\"", "break return result def run(self, test=False): \"\"\" Main execution function", "constructor \"\"\" self.list = None def insert(self, value): self.list =", "result = [] iter = self.start_iter() while True: result.append(iter.value) iter", "Linked list implementation in Python \"\"\" # Standard modules import" ]
[ "Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b,", "self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel = kernel", "TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r", "return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self,", "# Pick vp from model unless explicitly provided vp =", "receiver data # With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec,", "rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\"", "and encapsulates the time and space discretization for a given", "kernel : selects a visco-acoustic equation from the options below:", "Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp,", "object that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and", "source term. rec : SparseTimeFunction or array_like, optional The interpolated", "vp or self.model.vp if self.kernel == 'sls': # Execute operator", "'sls': # Execute operator and return wavefield and receiver data", "array-like The receiver data. Please note that these act as", "# With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r,", "source, wavefield and performance summary. \"\"\" # Create a new", "with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order,", "provided vp = vp or self.model.vp # Execute operator and", "k in v}) # Create the forward wavefield if not", "or array-like The resulting data for the interpolated at the", "pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable:", "return wavefield and receiver data # With Memory variable summary", "self.time_order == 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t,", ": VectorTimeFunction, optional The computed particle velocity. pa : TimeFunction,", "term in the adjoint run. srca : SparseTimeFunction or array-like", "in the adjoint run. srca : SparseTimeFunction or array-like The", "the injected source term. rec : SparseTimeFunction or array_like, optional", "------- Adjoint source, wavefield and performance summary. \"\"\" # Create", "inverse density. r : TimeFunction, optional The computed memory variable.", "summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt',", "Parameters ---------- src : SparseTimeFunction or array_like, optional Time series", "= p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) #", "return wavefield and receiver data if self.kernel == 'sls': #", "summary \"\"\" # Source term is read-only, so re-use the", "explicitly provided b = b or self.model.b qp = qp", "import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\"", "provides operators for seismic inversion problems and encapsulates the time", ": Function, optional The time-constant inverse density. r : TimeFunction,", "kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None):", "that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their", "# With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r,", "computed memory variable. Returns ------- Adjoint source, wavefield and performance", "self.time_order = time_order self._kwargs = kwargs @property def dt(self): return", "src = src or self.geometry.src # Create a new receiver", "p, r save_t = src.nt if save else None if", "else: # Execute operator and return wavefield and receiver data", "Blanch and Symes (1995) / Dutta and Schuster (2014) viscoacoustic", "- Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng", "to 'sls' 2nd order. \"\"\" def __init__(self, model, geometry, space_order=4,", "SparseTimeFunction or array_like, optional The interpolated receiver data. v :", "v : VectorTimeFunction, optional The computed particle velocity. r :", "optional Stores the computed wavefield. vp : Function or float,", "(2014) viscoacoustic equation 2nd order - Bai et al. (2014)", "self.model.b qp = qp or self.model.qp # Pick vp from", "spatial stencil discretisation. Defaults to 4. kernel : selects a", "a new receiver object to store the result rec =", "unless explicitly provided vp = vp or self.model.vp # Execute", "self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs)", "data objects for running an adjoint modelling operator. Parameters ----------", "return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward", "Execute operator and return wavefield and receiver data if self.kernel", "VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va})", "wavefield and receiver data # Without Memory variable summary =", "v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None,", "inversion problems and encapsulates the time and space discretization for", "= self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs)", ": Function or float, optional The time-constant velocity. qp :", "VectorTimeFunction, optional The computed particle velocity. pa : TimeFunction, optional", "Bai et al. (2014) viscoacoustic equation 'ren' - Ren et", ": selects a visco-acoustic equation from the options below: 'sls'", "Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order,", "staggered=NODE) b = b or self.model.b qp = qp or", "With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b,", "- Bai et al. (2014) viscoacoustic equation 'ren' - Ren", "forward wavefield if not provided p = p or TimeFunction(name=\"p\",", "class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for seismic", "a forward modelling operator. Parameters ---------- src : SparseTimeFunction or", "order - Bai et al. (2014) viscoacoustic equation 'ren' -", "= qp or self.model.qp # Pick vp from model unless", "summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt',", "examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object):", "factor. b : Function, optional The time-constant inverse density. r", "With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p,", "float, optional The time-constant velocity. save : bool, optional Whether", "SparseTimeFunction or array-like The receiver data. Please note that these", "(2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic", "ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self):", "b or self.model.b qp = qp or self.model.qp # Pick", "optional The computed memory variable. p : TimeFunction, optional Stores", "space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa = pa", "unless explicitly provided b = b or self.model.b qp =", "receiver data # Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec,", "equation Defaults to 'sls' 2nd order. \"\"\" def __init__(self, model,", "McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\"", "The resulting data for the interpolated at the original source", "not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order,", "data # With Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa,", "qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function that", "velocity. pa : TimeFunction, optional Stores the computed wavefield. vp", "staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid,", "a visco-acoustic equation from the options below: 'sls' (Standard Linear", "space discretization for a given problem setup. Parameters ---------- model", "__init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model", "Linear Solid) : 1st order - Blanch and Symes (1995)", "or self.geometry.src # Create a new receiver object to store", "P-wave quality factor. b : Function, optional The time-constant inverse", "k for k in va}) pa = pa or TimeFunction(name=\"pa\",", "r : TimeFunction, optional The computed memory variable. p :", "selects a visco-acoustic equation from the options below: 'sls' (Standard", "= time_order self._kwargs = kwargs @property def dt(self): return self.model.critical_dt", "modelling operator. Parameters ---------- rec : SparseTimeFunction or array-like The", "TimeFunction, optional The computed memory variable. p : TimeFunction, optional", "= src or self.geometry.src # Create a new receiver object", "Model Physical model with domain parameters. geometry : AcquisitionGeometry Geometry", "save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v}) #", "geometry self.space_order = space_order self.kernel = kernel self.time_order = time_order", "necessary data objects for running a forward modelling operator. Parameters", "TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b", "wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth", "re-use the default src = src or self.geometry.src # Create", "from devito.tools import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators", "kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry", "for the injected source term. rec : SparseTimeFunction or array_like,", "factor. b : Function, optional The time-constant inverse density. vp", "Pick physical parameters from model unless explicitly provided b =", "self.kernel == 'sls': # Execute operator and return wavefield and", "(Standard Linear Solid) : 1st order - Blanch and Symes", "The P-wave quality factor. b : Function, optional The time-constant", "op_fwd(self, save=None): \"\"\"Cached operator for forward runs with buffered wavefield\"\"\"", "src : SparseTimeFunction or array_like, optional Time series data for", "entire (unrolled) wavefield. Returns ------- Receiver, wavefield and performance summary", "= self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt),", "for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry,", "The computed memory variable. Returns ------- Adjoint source, wavefield and", "optional Stores the computed wavefield. qp : Function, optional The", "'ren' - Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' -", ": Model Physical model with domain parameters. geometry : AcquisitionGeometry", "**kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp,", "operator. Parameters ---------- rec : SparseTimeFunction or array-like The receiver", "b : Function, optional The time-constant inverse density. vp :", "or self.model.vp if self.kernel == 'sls': # Execute operator and", "# Create a new adjoint source and receiver symbol srca", "objects for running an adjoint modelling operator. Parameters ---------- rec", "function that creates the necessary data objects for running a", "= src.nt if save else None if self.time_order == 1:", "Function, optional The time-constant inverse density. r : TimeFunction, optional", "velocity. save : bool, optional Whether or not to save", "the necessary data objects for running a forward modelling operator.", "or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical", "computed memory variable. p : TimeFunction, optional Stores the computed", "data # With Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp,", "summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt),", "Create a new adjoint source and receiver symbol srca =", "self.space_order = space_order self.kernel = kernel self.time_order = time_order self._kwargs", "va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k", "== 'sls': # Execute operator and return wavefield and receiver", "grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r", "b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary", "optional The time-constant inverse density. r : TimeFunction, optional The", "'sls' (Standard Linear Solid) : 1st order - Blanch and", "= kernel self.time_order = time_order self._kwargs = kwargs @property def", "kwargs.update({k.name: k for k in va}) pa = pa or", "save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached", "the options below: 'sls' (Standard Linear Solid) : 1st order", "\"\"\"Cached operator for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model,", "the result rec = rec or self.geometry.rec # Create all", "in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order,", "r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b", "the spatial stencil discretisation. Defaults to 4. kernel : selects", "and return wavefield and receiver data # Without Memory variable", "or self.geometry.rec # Create all the fields v, p, r", "= geometry self.space_order = space_order self.kernel = kernel self.time_order =", "The time-constant inverse density. r : TimeFunction, optional The computed", "runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel,", "VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in", "time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None,", "Deng and McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd", "p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v,", "self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs)", "Dutta and Schuster (2014) viscoacoustic equation 2nd order - Bai", "Stores the computed wavefield. vp : Function or float, optional", "vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca, pa, va,", "# Create the forward wavefield if not provided p =", "and return wavefield and receiver data # With Memory variable", "@memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward runs with", "**self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return", "The computed particle velocity. pa : TimeFunction, optional Stores the", "------- Receiver, wavefield and performance summary \"\"\" # Source term", "---------- rec : SparseTimeFunction or array-like The receiver data. Please", "Source term is read-only, so re-use the default src =", "that creates the necessary data objects for running an adjoint", "to save the entire (unrolled) wavefield. Returns ------- Receiver, wavefield", ": TimeFunction, optional Stores the computed wavefield. vp : Function", "save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r", "or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va", ": AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction) and", "adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs):", "self.model.vp if self.kernel == 'sls': # Execute operator and return", "Symes (1995) / Dutta and Schuster (2014) viscoacoustic equation 2nd", "= space_order self.kernel = kernel self.time_order = time_order self._kwargs =", "b : Function, optional The time-constant inverse density. r :", "optional The computed particle velocity. r : TimeFunction, optional The", ": TimeFunction, optional Stores the computed wavefield. qp : Function,", "p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None,", "optional The interpolated receiver data. v : VectorTimeFunction, optional The", "the necessary data objects for running an adjoint modelling operator.", "source term in the adjoint run. srca : SparseTimeFunction or", "the interpolated at the original source location. va : VectorTimeFunction,", "that creates the necessary data objects for running a forward", "inverse density. vp : Function or float, optional The time-constant", "(1995) / Dutta and Schuster (2014) viscoacoustic equation 2nd order", "qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa,", "= r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) #", "or not to save the entire (unrolled) wavefield. Returns -------", "\"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model", "computed particle velocity. r : TimeFunction, optional The computed memory", "data # Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp,", "else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt',", "equation 2nd order - Bai et al. (2014) viscoacoustic equation", "et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan", "dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for", "return rec, p, v, summary def adjoint(self, rec, srca=None, va=None,", "as the source term in the adjoint run. srca :", "kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint", "Defaults to 4. kernel : selects a visco-acoustic equation from", "data if self.kernel == 'sls': # Execute operator and return", "Memory variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp,", "kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None,", "variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "of the spatial stencil discretisation. Defaults to 4. kernel :", "SparseTimeFunction or array-like The resulting data for the interpolated at", "data. v : VectorTimeFunction, optional The computed particle velocity. r", "return wavefield and receiver data # Without Memory variable summary", "time-constant velocity. qp : Function, optional The P-wave quality factor.", "and receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis,", "if self.time_order == 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid,", "series data for the injected source term. rec : SparseTimeFunction", "r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary =", "viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\" def __init__(self,", "rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else:", "\"\"\" Adjoint modelling function that creates the necessary data objects", "= vp or self.model.vp # Execute operator and return wavefield", "and receiver data # Without Memory variable summary = self.op_fwd(save).apply(src=src,", "Pick vp from model unless explicitly provided vp = vp", "array_like, optional The interpolated receiver data. v : VectorTimeFunction, optional", "receiver data. v : VectorTimeFunction, optional The computed particle velocity.", "an adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction or", "or self.model.qp # Pick vp from model unless explicitly provided", "data objects for running a forward modelling operator. Parameters ----------", "qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: #", "Create the forward wavefield if not provided p = p", "r : TimeFunction, optional The computed memory variable. Returns -------", "encapsulates the time and space discretization for a given problem", "space_order=self.space_order, staggered=NODE) b = b or self.model.b qp = qp", "optional Order of the spatial stencil discretisation. Defaults to 4.", "and Symes (1995) / Dutta and Schuster (2014) viscoacoustic equation", "ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for seismic inversion", "data. Please note that these act as the source term", "with domain parameters. geometry : AcquisitionGeometry Geometry object that contains", "receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions)", "data for the injected source term. rec : SparseTimeFunction or", "discretization for a given problem setup. Parameters ---------- model :", "srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order", "time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va = va or", "dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp,", ": SparseTimeFunction or array-like The receiver data. Please note that", "examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that", "model with domain parameters. geometry : AcquisitionGeometry Geometry object that", "running an adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction", "the source term in the adjoint run. srca : SparseTimeFunction", "bool, optional Whether or not to save the entire (unrolled)", "model unless explicitly provided b = b or self.model.b qp", "AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators for", "\"\"\" # Create a new adjoint source and receiver symbol", "from the options below: 'sls' (Standard Linear Solid) : 1st", "srca : SparseTimeFunction or array-like The resulting data for the", "adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs)", "space_order=self.space_order, staggered=NODE) # Memory variable: r = r or TimeFunction(name=\"r\",", "equation 'ren' - Ren et al. (2014) viscoacoustic equation 'deng_mcmechan'", "options below: 'sls' (Standard Linear Solid) : 1st order -", "Function or float, optional The time-constant velocity. qp : Function,", ": Function, optional The P-wave quality factor. b : Function,", "seismic inversion problems and encapsulates the time and space discretization", "al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007)", ": SparseTimeFunction or array_like, optional Time series data for the", "space_order=self.space_order) kwargs.update({k.name: k for k in v}) # Create the", "p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator", "runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def", "1st order - Blanch and Symes (1995) / Dutta and", "The computed particle velocity. r : TimeFunction, optional The computed", "term. rec : SparseTimeFunction or array_like, optional The interpolated receiver", "or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k", "save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from model", "devito import VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth from", "time_order self._kwargs = kwargs @property def dt(self): return self.model.critical_dt @memoized_meth", "PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va =", "\"\"\" Forward modelling function that creates the necessary data objects", "Parameters ---------- model : Model Physical model with domain parameters.", "op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry,", "operator for forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save,", "geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry", "**self._kwargs) def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None,", "operator and return wavefield and receiver data # With Memory", "equation from the options below: 'sls' (Standard Linear Solid) :", "**kwargs): \"\"\" Forward modelling function that creates the necessary data", "result rec = rec or self.geometry.rec # Create all the", "v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward", "from model unless explicitly provided b = b or self.model.b", "def forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None,", "optional The P-wave quality factor. b : Function, optional The", "default src = src or self.geometry.src # Create a new", "self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return", "# Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order,", "and receivers (SparseTimeFunction) and their position. space_order : int, optional", "for a given problem setup. Parameters ---------- model : Model", ": int, optional Order of the spatial stencil discretisation. Defaults", "int, optional Order of the spatial stencil discretisation. Defaults to", "wavefield. qp : Function, optional The P-wave quality factor. b", "explicitly provided vp = vp or self.model.vp # Execute operator", "b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca,", "qp = qp or self.model.qp # Pick vp from model", "= self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs)", "time-constant inverse density. vp : Function or float, optional The", "TimeFunction, optional Stores the computed wavefield. vp : Function or", "Function, optional The P-wave quality factor. b : Function, optional", "problems and encapsulates the time and space discretization for a", "vp : Function or float, optional The time-constant velocity. save", "physical parameters from model unless explicitly provided b = b", "# Source term is read-only, so re-use the default src", "time-constant velocity. save : bool, optional Whether or not to", "time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa =", "new adjoint source and receiver symbol srca = srca or", "== 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order)", "Create a new receiver object to store the result rec", "if self.time_order == 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid,", "Stores the computed wavefield. qp : Function, optional The P-wave", "viscoacoustic equation 'ren' - Ren et al. (2014) viscoacoustic equation", "function that creates the necessary data objects for running an", "self.kernel = kernel self.time_order = time_order self._kwargs = kwargs @property", "or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable:", "optional The time-constant velocity. save : bool, optional Whether or", "\"\"\" Solver object that provides operators for seismic inversion problems", "import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides", "AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction) and receivers", "Time series data for the injected source term. rec :", "from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object", "equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation Defaults", "(2007) viscoacoustic equation Defaults to 'sls' 2nd order. \"\"\" def", "else None if self.time_order == 1: v = v or", "'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation Defaults to", "new receiver object to store the result rec = rec", "self.dt), **kwargs) else: # Execute operator and return wavefield and", "Solver object that provides operators for seismic inversion problems and", "space_order : int, optional Order of the spatial stencil discretisation.", "particle velocity. r : TimeFunction, optional The computed memory variable.", "grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b qp", "if self.kernel == 'sls': # Execute operator and return wavefield", "pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary", ": VectorTimeFunction, optional The computed particle velocity. r : TimeFunction,", "memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator)", "unless explicitly provided vp = vp or self.model.vp if self.kernel", "Parameters ---------- rec : SparseTimeFunction or array-like The receiver data.", "float, optional The time-constant velocity. qp : Function, optional The", "setup. Parameters ---------- model : Model Physical model with domain", "p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel,", "term is read-only, so re-use the default src = src", "or float, optional The time-constant velocity. qp : Function, optional", "parameters from model unless explicitly provided b = b or", "receivers (SparseTimeFunction) and their position. space_order : int, optional Order", ": TimeFunction, optional The computed memory variable. Returns ------- Adjoint", "time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\"", "forward modelling operator. Parameters ---------- src : SparseTimeFunction or array_like,", "velocity. qp : Function, optional The P-wave quality factor. b", "coordinates=self.geometry.src_positions) if self.time_order == 1: va = va or VectorTimeFunction(name=\"va\",", "staggered=NODE) # Pick physical parameters from model unless explicitly provided", "@property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached", "# Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t,", "r=None, **kwargs): \"\"\" Adjoint modelling function that creates the necessary", "time and space discretization for a given problem setup. Parameters", "model : Model Physical model with domain parameters. geometry :", "or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in", "save else None if self.time_order == 1: v = v", "vp = vp or self.model.vp # Execute operator and return", "space_order self.kernel = kernel self.time_order = time_order self._kwargs = kwargs", "interpolated receiver data. v : VectorTimeFunction, optional The computed particle", "quality factor. b : Function, optional The time-constant inverse density.", ": TimeFunction, optional The computed memory variable. p : TimeFunction,", "rec or self.geometry.rec # Create all the fields v, p,", "vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary def", "va : VectorTimeFunction, optional The computed particle velocity. pa :", ": 1st order - Blanch and Symes (1995) / Dutta", "AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None,", "rec, p, v, summary def adjoint(self, rec, srca=None, va=None, pa=None,", "VectorTimeFunction, optional The computed particle velocity. r : TimeFunction, optional", "**kwargs): \"\"\" Adjoint modelling function that creates the necessary data", "for running an adjoint modelling operator. Parameters ---------- rec :", "vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec,", "variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order,", "and performance summary \"\"\" # Source term is read-only, so", "v, p, r save_t = src.nt if save else None", "save=None): \"\"\"Cached operator for forward runs with buffered wavefield\"\"\" return", "computed wavefield. qp : Function, optional The P-wave quality factor.", "or self.model.vp # Execute operator and return wavefield and receiver", "1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name:", "import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator,", "order - Blanch and Symes (1995) / Dutta and Schuster", "computed wavefield. vp : Function or float, optional The time-constant", "domain parameters. geometry : AcquisitionGeometry Geometry object that contains the", "provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order,", "grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r =", "pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca, pa,", "r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick", "variable summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp,", "\"\"\" # Source term is read-only, so re-use the default", "optional Time series data for the injected source term. rec", "geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator", "and receiver data # With Memory variable summary = self.op_fwd(save).apply(src=src,", "k for k in v}) # Create the forward wavefield", "b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and", "qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p,", ": bool, optional Whether or not to save the entire", "va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "\"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order,", "pa : TimeFunction, optional Stores the computed wavefield. vp :", "order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs):", "adjoint source and receiver symbol srca = srca or PointSource(name='srca',", "4. kernel : selects a visco-acoustic equation from the options", "provided vp = vp or self.model.vp if self.kernel == 'sls':", "interpolated at the original source location. va : VectorTimeFunction, optional", "= v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k", "receiver object to store the result rec = rec or", "**kwargs) return rec, p, v, summary def adjoint(self, rec, srca=None,", "(unrolled) wavefield. Returns ------- Receiver, wavefield and performance summary \"\"\"", "and McMechan (2007) viscoacoustic equation Defaults to 'sls' 2nd order.", "self.geometry.src # Create a new receiver object to store the", "model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\")", "p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory", "necessary data objects for running an adjoint modelling operator. Parameters", "position. space_order : int, optional Order of the spatial stencil", "model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel =", "self.model.qp # Pick vp from model unless explicitly provided vp", "self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator for forward runs", "optional The time-constant inverse density. vp : Function or float,", "Whether or not to save the entire (unrolled) wavefield. Returns", "the entire (unrolled) wavefield. Returns ------- Receiver, wavefield and performance", "and space discretization for a given problem setup. Parameters ----------", "fields v, p, r save_t = src.nt if save else", "1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order)", "geometry : AcquisitionGeometry Geometry object that contains the source (SparseTimeFunction)", "rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca,", "srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1:", "the original source location. va : VectorTimeFunction, optional The computed", "The time-constant velocity. save : bool, optional Whether or not", "creates the necessary data objects for running an adjoint modelling", "SparseTimeFunction or array_like, optional Time series data for the injected", "object to store the result rec = rec or self.geometry.rec", "computed particle velocity. pa : TimeFunction, optional Stores the computed", "note that these act as the source term in the", "wavefield and receiver data if self.kernel == 'sls': # Execute", "- Deng and McMechan (2007) viscoacoustic equation Defaults to 'sls'", "space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None, r=None,", "buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs)", "/ Dutta and Schuster (2014) viscoacoustic equation 2nd order -", "wavefield. vp : Function or float, optional The time-constant velocity.", "the computed wavefield. vp : Function or float, optional The", "creates the necessary data objects for running a forward modelling", "rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\"", "---------- model : Model Physical model with domain parameters. geometry", "The interpolated receiver data. v : VectorTimeFunction, optional The computed", "# Create a new receiver object to store the result", "optional Whether or not to save the entire (unrolled) wavefield.", "b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function that creates", "viscoacoustic equation 'deng_mcmechan' - Deng and McMechan (2007) viscoacoustic equation", "provided b = b or self.model.b qp = qp or", "dt=kwargs.pop('dt', self.dt), **kwargs) return rec, p, v, summary def adjoint(self,", "save the entire (unrolled) wavefield. Returns ------- Receiver, wavefield and", "kernel self.time_order = time_order self._kwargs = kwargs @property def dt(self):", "for adjoint runs\"\"\" return AdjointOperator(self.model, save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order,", "self.geometry.rec # Create all the fields v, p, r save_t", "== 1: v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order,", "to 4. kernel : selects a visco-acoustic equation from the", "the time and space discretization for a given problem setup.", "so re-use the default src = src or self.geometry.src #", "vp = vp or self.model.vp if self.kernel == 'sls': #", "wavefield. Returns ------- Receiver, wavefield and performance summary \"\"\" #", "the fields v, p, r save_t = src.nt if save", ": Function or float, optional The time-constant velocity. save :", "run. srca : SparseTimeFunction or array-like The resulting data for", "Function or float, optional The time-constant velocity. save : bool,", "wavefield and receiver data # With Memory variable summary =", "save=None, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None,", "operators for seismic inversion problems and encapsulates the time and", "source and receiver symbol srca = srca or PointSource(name='srca', grid=self.model.grid,", "self._kwargs = kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def", "the adjoint run. srca : SparseTimeFunction or array-like The resulting", "a given problem setup. Parameters ---------- model : Model Physical", "# Create all the fields v, p, r save_t =", "TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters", "r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE)", "Forward modelling function that creates the necessary data objects for", "et al. (2014) viscoacoustic equation 'ren' - Ren et al.", "objects for running a forward modelling operator. Parameters ---------- src", "problem setup. Parameters ---------- model : Model Physical model with", "modelling operator. Parameters ---------- src : SparseTimeFunction or array_like, optional", "variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, r=r, p=p, b=b, vp=vp,", "a new adjoint source and receiver symbol srca = srca", "b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return srca, pa, va, summary", "devito.tools import memoized_meth from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import", "Physical model with domain parameters. geometry : AcquisitionGeometry Geometry object", "and Schuster (2014) viscoacoustic equation 2nd order - Bai et", ": SparseTimeFunction or array_like, optional The interpolated receiver data. v", "space_order=self.space_order, staggered=NODE) # Pick physical parameters from model unless explicitly", "array_like, optional Time series data for the injected source term.", "(ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver object that provides operators", "self.geometry = geometry self.space_order = space_order self.kernel = kernel self.time_order", "r save_t = src.nt if save else None if self.time_order", "= self.op_adj().apply(src=srca, rec=rec, pa=pa, r=r, b=b, vp=vp, qp=qp, dt=kwargs.pop('dt', self.dt),", "@memoized_meth def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model,", "space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def op_adj(self): \"\"\"Cached operator for", "source location. va : VectorTimeFunction, optional The computed particle velocity.", "pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function", "Order of the spatial stencil discretisation. Defaults to 4. kernel", "The time-constant inverse density. vp : Function or float, optional", "grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in va}) pa", "viscoacoustic equation 2nd order - Bai et al. (2014) viscoacoustic", "p : TimeFunction, optional Stores the computed wavefield. qp :", "time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or self.model.b qp =", "variable. p : TimeFunction, optional Stores the computed wavefield. qp", "Returns ------- Receiver, wavefield and performance summary \"\"\" # Source", "memory variable. p : TimeFunction, optional Stores the computed wavefield.", "pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) #", "or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r", "the default src = src or self.geometry.src # Create a", "self.model.vp # Execute operator and return wavefield and receiver data", "contains the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position.", "summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt),", "model unless explicitly provided vp = vp or self.model.vp if", "v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for", "TimeFunction, optional Stores the computed wavefield. qp : Function, optional", "self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order", "from devito import VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth", "save_t = src.nt if save else None if self.time_order ==", "rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) return rec,", "not to save the entire (unrolled) wavefield. Returns ------- Receiver,", "density. vp : Function or float, optional The time-constant velocity.", "Defaults to 'sls' 2nd order. \"\"\" def __init__(self, model, geometry,", "# Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p,", "and receiver data # With Memory variable summary = self.op_adj().apply(src=srca,", "act as the source term in the adjoint run. srca", "for running a forward modelling operator. Parameters ---------- src :", "geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) def forward(self, src=None, rec=None, v=None,", "self.dt), **kwargs) return rec, p, v, summary def adjoint(self, rec,", "r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute", "self.dt), **kwargs) else: summary = self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b,", "and receiver data if self.kernel == 'sls': # Execute operator", "v}) # Create the forward wavefield if not provided p", "at the original source location. va : VectorTimeFunction, optional The", "src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs):", "dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and return wavefield", "qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that creates", "their position. space_order : int, optional Order of the spatial", "return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order, kernel=self.kernel, time_order=self.time_order, **self._kwargs) @memoized_meth def", "optional The computed memory variable. Returns ------- Adjoint source, wavefield", "p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling function", "discretisation. Defaults to 4. kernel : selects a visco-acoustic equation", "v = v or VectorTimeFunction(name=\"v\", grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name:", "variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b, vp=vp, dt=kwargs.pop('dt',", "symbol srca = srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if", "Schuster (2014) viscoacoustic equation 2nd order - Bai et al.", "is read-only, so re-use the default src = src or", "(SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order : int,", "for seismic inversion problems and encapsulates the time and space", "The receiver data. Please note that these act as the", "that these act as the source term in the adjoint", ": SparseTimeFunction or array-like The resulting data for the interpolated", "location. va : VectorTimeFunction, optional The computed particle velocity. pa", "Without Memory variable summary = self.op_fwd(save).apply(src=src, rec=rec, qp=qp, p=p, b=b,", "optional The time-constant velocity. qp : Function, optional The P-wave", "VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic import", "Returns ------- Adjoint source, wavefield and performance summary. \"\"\" #", "and performance summary. \"\"\" # Create a new adjoint source", "receiver data if self.kernel == 'sls': # Execute operator and", "if not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid, save=save_t,", "the forward wavefield if not provided p = p or", "save : bool, optional Whether or not to save the", "adjoint modelling operator. Parameters ---------- rec : SparseTimeFunction or array-like", "self.time_order == 1: va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order,", "2nd order - Bai et al. (2014) viscoacoustic equation 'ren'", "and their position. space_order : int, optional Order of the", "time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from model unless", "wavefield if not provided p = p or TimeFunction(name=\"p\", grid=self.model.grid,", "vp or self.model.vp # Execute operator and return wavefield and", "Receiver, wavefield and performance summary \"\"\" # Source term is", "the source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order", "Adjoint modelling function that creates the necessary data objects for", "that provides operators for seismic inversion problems and encapsulates the", "or float, optional The time-constant velocity. save : bool, optional", "src.nt if save else None if self.time_order == 1: v", "None if self.time_order == 1: v = v or VectorTimeFunction(name=\"v\",", "wavefield and performance summary. \"\"\" # Create a new adjoint", "NODE from devito.tools import memoized_meth from examples.seismic import PointSource from", "Geometry object that contains the source (SparseTimeFunction) and receivers (SparseTimeFunction)", "Memory variable: r = r or TimeFunction(name=\"r\", grid=self.model.grid, save=save_t, time_order=self.time_order,", "def op_adj(self): \"\"\"Cached operator for adjoint runs\"\"\" return AdjointOperator(self.model, save=None,", "al. (2014) viscoacoustic equation 'ren' - Ren et al. (2014)", "forward runs with buffered wavefield\"\"\" return ForwardOperator(self.model, save=save, geometry=self.geometry, space_order=self.space_order,", "time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v}) # Create", "variable. Returns ------- Adjoint source, wavefield and performance summary. \"\"\"", "qp or self.model.qp # Pick vp from model unless explicitly", "---------- src : SparseTimeFunction or array_like, optional Time series data", "density. r : TimeFunction, optional The computed memory variable. Returns", "the computed wavefield. qp : Function, optional The P-wave quality", "= rec or self.geometry.rec # Create all the fields v,", "or array-like The receiver data. Please note that these act", "wavefield and performance summary \"\"\" # Source term is read-only,", "**kwargs) else: # Execute operator and return wavefield and receiver", "Function, optional The time-constant inverse density. vp : Function or", "= srca or PointSource(name='srca', grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order ==", "given problem setup. Parameters ---------- model : Model Physical model", "vp : Function or float, optional The time-constant velocity. qp", "Adjoint source, wavefield and performance summary. \"\"\" # Create a", "performance summary. \"\"\" # Create a new adjoint source and", "or self.model.b qp = qp or self.model.qp # Pick vp", "all the fields v, p, r save_t = src.nt if", "if save else None if self.time_order == 1: v =", "array-like The resulting data for the interpolated at the original", "def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2, **kwargs): self.model =", "k in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order,", "summary def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None,", "= pa or TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory", "Ren et al. (2014) viscoacoustic equation 'deng_mcmechan' - Deng and", "original source location. va : VectorTimeFunction, optional The computed particle", "# Pick physical parameters from model unless explicitly provided b", "(SparseTimeFunction) and their position. space_order : int, optional Order of", "= va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for", "srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint", "qp : Function, optional The P-wave quality factor. b :", "velocity. r : TimeFunction, optional The computed memory variable. p", "Execute operator and return wavefield and receiver data # Without", "read-only, so re-use the default src = src or self.geometry.src", "operator. Parameters ---------- src : SparseTimeFunction or array_like, optional Time", "resulting data for the interpolated at the original source location.", "# Execute operator and return wavefield and receiver data if", "grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Pick physical parameters from", "time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order", "performance summary \"\"\" # Source term is read-only, so re-use", "for k in va}) pa = pa or TimeFunction(name=\"pa\", grid=self.model.grid,", "rec : SparseTimeFunction or array-like The receiver data. Please note", "source (SparseTimeFunction) and receivers (SparseTimeFunction) and their position. space_order :", "The computed memory variable. p : TimeFunction, optional Stores the", "particle velocity. pa : TimeFunction, optional Stores the computed wavefield.", "parameters. geometry : AcquisitionGeometry Geometry object that contains the source", "stencil discretisation. Defaults to 4. kernel : selects a visco-acoustic", "summary. \"\"\" # Create a new adjoint source and receiver", "TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic import PointSource", "adjoint run. srca : SparseTimeFunction or array-like The resulting data", "vp=None, save=None, **kwargs): \"\"\" Forward modelling function that creates the", "def adjoint(self, rec, srca=None, va=None, pa=None, vp=None, qp=None, b=None, r=None,", "operator and return wavefield and receiver data if self.kernel ==", "receiver data # With Memory variable summary = self.op_adj().apply(src=srca, rec=rec,", "injected source term. rec : SparseTimeFunction or array_like, optional The", "store the result rec = rec or self.geometry.rec # Create", "operator and return wavefield and receiver data # Without Memory", "# Execute operator and return wavefield and receiver data #", "model unless explicitly provided vp = vp or self.model.vp #", "for the interpolated at the original source location. va :", "grid=self.model.grid, time_range=self.geometry.time_axis, coordinates=self.geometry.src_positions) if self.time_order == 1: va = va", "va=None, pa=None, vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling", "Please note that these act as the source term in", "vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else: # Execute operator and return", "modelling function that creates the necessary data objects for running", "'sls' 2nd order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls',", "- Blanch and Symes (1995) / Dutta and Schuster (2014)", "rec = rec or self.geometry.rec # Create all the fields", "def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self, save=None): \"\"\"Cached operator", "to store the result rec = rec or self.geometry.rec #", "save=None, **kwargs): \"\"\" Forward modelling function that creates the necessary", "receiver data. Please note that these act as the source", "object that provides operators for seismic inversion problems and encapsulates", "rec=rec, qp=qp, r=r, p=p, b=b, vp=vp, dt=kwargs.pop('dt', self.dt), **kwargs) else:", "data for the interpolated at the original source location. va", "for k in v}) # Create the forward wavefield if", "vp=None, qp=None, b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that", "time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r = r or", "running a forward modelling operator. Parameters ---------- src : SparseTimeFunction", "2nd order. \"\"\" def __init__(self, model, geometry, space_order=4, kernel='sls', time_order=2,", "PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class ViscoacousticWaveSolver(object): \"\"\" Solver", "these act as the source term in the adjoint run.", "= vp or self.model.vp if self.kernel == 'sls': # Execute", "visco-acoustic equation from the options below: 'sls' (Standard Linear Solid)", "or array_like, optional Time series data for the injected source", "b=None, r=None, **kwargs): \"\"\" Adjoint modelling function that creates the", ": Function, optional The time-constant inverse density. vp : Function", "(2014) viscoacoustic equation 'ren' - Ren et al. (2014) viscoacoustic", "optional The computed particle velocity. pa : TimeFunction, optional Stores", "from examples.seismic import PointSource from examples.seismic.viscoacoustic.operators import (ForwardOperator, AdjointOperator) class", "Create all the fields v, p, r save_t = src.nt", "r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b", "b = b or self.model.b qp = qp or self.model.qp", "or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b = b or", "space_order=4, kernel='sls', time_order=2, **kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry =", "grid=self.model.grid, save=save_t, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k for k in v})", "in v}) # Create the forward wavefield if not provided", "or array_like, optional The interpolated receiver data. v : VectorTimeFunction,", "= kwargs @property def dt(self): return self.model.critical_dt @memoized_meth def op_fwd(self,", "from model unless explicitly provided vp = vp or self.model.vp", "kwargs.update({k.name: k for k in v}) # Create the forward", "= r or TimeFunction(name=\"r\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) b =", "= b or self.model.b qp = qp or self.model.qp #", "TimeFunction(name=\"pa\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order, staggered=NODE) # Memory variable: r =", "The time-constant velocity. qp : Function, optional The P-wave quality", "def op_fwd(self, save=None): \"\"\"Cached operator for forward runs with buffered", "r=None, p=None, qp=None, b=None, vp=None, save=None, **kwargs): \"\"\" Forward modelling", "src or self.geometry.src # Create a new receiver object to", "explicitly provided vp = vp or self.model.vp if self.kernel ==", "import VectorTimeFunction, TimeFunction, NODE from devito.tools import memoized_meth from examples.seismic", "and return wavefield and receiver data if self.kernel == 'sls':", "memory variable. Returns ------- Adjoint source, wavefield and performance summary.", "forward(self, src=None, rec=None, v=None, r=None, p=None, qp=None, b=None, vp=None, save=None,", "vp from model unless explicitly provided vp = vp or", "= model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order = space_order self.kernel", "Execute operator and return wavefield and receiver data # With", "time-constant inverse density. r : TimeFunction, optional The computed memory", "va = va or VectorTimeFunction(name=\"va\", grid=self.model.grid, time_order=self.time_order, space_order=self.space_order) kwargs.update({k.name: k", "self.op_adj().apply(src=srca, rec=rec, pa=pa, vp=vp, b=b, qp=qp, dt=kwargs.pop('dt', self.dt), **kwargs) return", "Solid) : 1st order - Blanch and Symes (1995) /", "below: 'sls' (Standard Linear Solid) : 1st order - Blanch", "rec : SparseTimeFunction or array_like, optional The interpolated receiver data.", "**kwargs): self.model = model self.model._initialize_bcs(bcs=\"mask\") self.geometry = geometry self.space_order =", "TimeFunction, optional The computed memory variable. Returns ------- Adjoint source," ]
[ "') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary =", "import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList", "apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with", "itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList)", "f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if", "= [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f:", "as pd import os from tqdm import tqdm from collections", "mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList = [] def", "os from tqdm import tqdm from collections import defaultdict from", "= pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(),", "desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f:", "import tqdm from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder", "'w+') as f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str,", "= line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder()", "defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath", "in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit()", "'') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te", "df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] =", "= myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda", "\"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx,", "itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as", "collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import", "open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v in tqdm(user_category.items()):", "def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df =", "loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in", "line = line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates)))", "from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList = []", "for line in f.readlines(): line = line.replace('\\n', '') cates =", "columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df", "v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__':", "cates))) def myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df", "row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath,", "generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k,", "TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\" itemSetList =", "open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in f.readlines(): line", "cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te =", "pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return", "if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set)", "import pandas as pd import os from tqdm import tqdm", "f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df", "'__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035,", "line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori(): te = TransactionEncoder() te_ary", "= line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def", "frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x))", "pandas as pd import os from tqdm import tqdm from", "f: for line in f.readlines(): line = line.replace('\\n', '') cates", "total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as", "if __name__ == '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets", "in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"),", "dataPath = \"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath,", "te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_)", "for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__", "myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x:", "'.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df =", "== '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df,", "apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x)) print(frequent_itemsets[(frequent_itemsets['length'] >=", "f.readlines(): line = line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int,", "\"aprioriData.csv\"), 'r') as f: for line in f.readlines(): line =", "pd import os from tqdm import tqdm from collections import", "df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\")", "import os from tqdm import tqdm from collections import defaultdict", "for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID'])", "as f: for k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n')", "import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori", "= pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")):", "from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath =", "= te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit():", "def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category", "df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in", "__name__ == '__main__': dataInit() loadDataSet() df = myApriori() frequent_itemsets =", "in f.readlines(): line = line.replace('\\n', '') cates = line.split(' ')", "TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df", "idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with", "min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x)) print(frequent_itemsets[(frequent_itemsets['length'] >= 2)])", "data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for", "\"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r')", "os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for", "= defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data", "from tqdm import tqdm from collections import defaultdict from mlxtend.preprocessing", "tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"): user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+')", "\"aprioriData.csv\"), 'w+') as f: for k, v in tqdm(user_category.items()): f.write('", "as f: for line in f.readlines(): line = line.replace('\\n', '')", "return df = pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row", "tqdm import tqdm from collections import defaultdict from mlxtend.preprocessing import", "dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df = pd.read_csv(\"data/static/static.csv\") user_category =", "with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line in f.readlines():", "= apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x)) print(frequent_itemsets[(frequent_itemsets['length']", "tqdm from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from", "def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for line", "with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v in", "dataInit() loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True)", "[] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"), 'r') as f: for", "tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet()", "from collections import defaultdict from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns", "'r') as f: for line in f.readlines(): line = line.replace('\\n',", "import apriori dataPath = \"data/static\" itemSetList = [] def loadDataSet():", "return df def dataInit(): if os.path.exists(os.path.join(dataPath, \"aprioriData.csv\")): return df =", "defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category data generate\"):", "k, v in tqdm(user_category.items()): f.write(' '.join(sorted(list(map(str, v))))+'\\n') if __name__ ==", "loadDataSet() df = myApriori() frequent_itemsets = apriori(df, min_support=0.0035, use_colnames=True) frequent_itemsets['length']", "line in f.readlines(): line = line.replace('\\n', '') cates = line.split('", "= TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return", "df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if os.path.exists(os.path.join(dataPath,", "mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori dataPath = \"data/static\"", "user_category[row['USER_ID']].add(row['CATEGORY_ID']) with open(os.path.join(dataPath, \"aprioriData.csv\"), 'w+') as f: for k, v", "te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def", "myApriori(): te = TransactionEncoder() te_ary = te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary,", "te.fit(itemSetList).transform(itemSetList) df = pd.DataFrame(te_ary, columns=te.columns_) return df def dataInit(): if", "user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"category", "v))))+'\\n') if __name__ == '__main__': dataInit() loadDataSet() df = myApriori()", "= \"data/static\" itemSetList = [] def loadDataSet(): with open(os.path.join(dataPath, \"aprioriData.csv\"),", "pd.read_csv(\"data/static/static.csv\") user_category = defaultdict(set) for idx, row in tqdm(df.iterrows(), total=df.shape[0],", "line.replace('\\n', '') cates = line.split(' ') itemSetList.append(list(map(int, cates))) def myApriori():" ]
[ "= request.get_json() name = 'World' if request_json and 'name' in", "name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET,", "+ name + '! From GCP + Python', 200, headers)", "request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers':", "= request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST',", "= 'World' if request_json and 'name' in request_json: name =", "'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' +", "'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello", "'Content-Type' } return ('Hello ' + name + '! From", "name = 'World' if request_json and 'name' in request_json: name", "'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name", "POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name +", "'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello ' + name + '!", "request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods':", "request.get_json() name = 'World' if request_json and 'name' in request_json:", "and 'name' in request_json: name = request_json['name'] headers = {", "'World' if request_json and 'name' in request_json: name = request_json['name']", "request_json = request.get_json() name = 'World' if request_json and 'name'", "return ('Hello ' + name + '! From GCP +", "request_json and 'name' in request_json: name = request_json['name'] headers =", "def hello_world(request): request_json = request.get_json() name = 'World' if request_json", "hello_world(request): request_json = request.get_json() name = 'World' if request_json and", "= { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' }", "headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type'", "{ 'Access-Control-Allow-Origin': 'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return", "' + name + '! From GCP + Python', 200,", "'name' in request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin':", "in request_json: name = request_json['name'] headers = { 'Access-Control-Allow-Origin': 'https://furikuri.net',", "('Hello ' + name + '! From GCP + Python',", "} return ('Hello ' + name + '! From GCP", "'https://furikuri.net', 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type' } return ('Hello '", "if request_json and 'name' in request_json: name = request_json['name'] headers", "<reponame>FuriKuri/faas-playground def hello_world(request): request_json = request.get_json() name = 'World' if" ]
[ "Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR =", "abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params)", "ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS =", "TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage,", "TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json'))", "is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set", "ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR,", "= TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR,", "Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__)", "'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage(", "CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR", "from tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer,", "from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage", "address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def tonos_punch():", "= os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints", "CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS,", "client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client", "input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params", "'0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config)", "= ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client =", "function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set)", "'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf']", "= '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client =", "encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage(", "ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False)", "giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest':", "= ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params,", "process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def tonos_punch(): send_grams( address='0:b5e9240fc2d2f1ff8cbb1d1dee7fb7cae155e5f6320e585fcc685698994a19a5')", "import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig, \\", "= TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi", "call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def tonos_punch(): send_grams(", "= Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address})", "sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi = Abi.from_path(", "= ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def", "\\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples')", "os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints =", "str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant',", "call_set = CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi,", "['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address:", "= os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config", "async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str):", "TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False) def send_grams(address: str): giver_abi =", "ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS", "import os from tonclient.client import TonClient from tonclient.types import Abi,", "tonclient.types import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR", "<filename>tonclient/test/helpers.py<gh_stars>10-100 import os from tonclient.client import TonClient from tonclient.types import", "GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client", "tonclient.client import TonClient from tonclient.types import Abi, CallSet, Signer, ClientConfig,", "def send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set =", "SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config = ClientConfig()", "= CallSet( function_name='grant', input={'dest': address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(),", "Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params", "path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet( function_name='grant', input={'dest': address}) encode_params =", "send_grams(address: str): giver_abi = Abi.from_path( path=os.path.join(SAMPLES_DIR, 'Giver.abi.json')) call_set = CallSet(", "client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config, is_core_async=False)", "address}) encode_params = ParamsOfEncodeMessage( abi=giver_abi, signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params =", "BASE_DIR = os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23'", "signer=Signer.NoSigner(), address=GIVER_ADDRESS, call_set=call_set) process_params = ParamsOfProcessMessage( message_encode_params=encode_params, send_events=False) async_core_client.processing.process_message(params=process_params) def", "ClientConfig() client_config.network.endpoints = ['https://tonos.freeton.surf'] async_core_client = TonClient(config=client_config) sync_core_client = TonClient(config=client_config,", "os from tonclient.client import TonClient from tonclient.types import Abi, CallSet,", "import Abi, CallSet, Signer, ClientConfig, \\ ParamsOfEncodeMessage, ParamsOfProcessMessage BASE_DIR =", "os.path.dirname(__file__) SAMPLES_DIR = os.path.join(BASE_DIR, 'samples') GIVER_ADDRESS = '0:f5c2510bfe407363cb1db6b9d7bc1184a05f8b343aeaa828189c580e8569ee23' client_config =" ]
[ "import i18n from flask import request from flask_kajiki import render_template", "request.path == '/test_i18n': return s.upper() return s i18n.gettext = gettext", "so we test for request path that only functions from", "DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert rendered ==", "render_template # N. B. settting i18n.gettext would affect tests from", "= render_template('i18n.html') # TODO DOCTYPE; see also render_args expected =", "test for request path that only functions from this module", "only functions from this module could set def gettext(s): if", "request path that only functions from this module could set", "this module could set def gettext(s): if request.path == '/test_i18n':", "= gettext def test_does_translations(app): \"\"\"Callback interface is able to inject", "import request from flask_kajiki import render_template # N. B. settting", "flask_kajiki import render_template # N. B. settting i18n.gettext would affect", "inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO", "TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert rendered", "is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered =", "gettext(s): if request.path == '/test_i18n': return s.upper() return s i18n.gettext", "def test_does_translations(app): \"\"\"Callback interface is able to inject Translator filter\"\"\"", "able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html')", "we test for request path that only functions from this", "for request path that only functions from this module could", "from this module could set def gettext(s): if request.path ==", "def gettext(s): if request.path == '/test_i18n': return s.upper() return s", "s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface", "from flask_kajiki import render_template # N. B. settting i18n.gettext would", "s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is able", "app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args", "modules, # so we test for request path that only", "interface is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered", "return s.upper() return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback", "from all modules, # so we test for request path", "import render_template # N. B. settting i18n.gettext would affect tests", "functions from this module could set def gettext(s): if request.path", "render_template('i18n.html') # TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>'", "N. B. settting i18n.gettext would affect tests from all modules,", "set def gettext(s): if request.path == '/test_i18n': return s.upper() return", "'/test_i18n': return s.upper() return s i18n.gettext = gettext def test_does_translations(app):", "test_does_translations(app): \"\"\"Callback interface is able to inject Translator filter\"\"\" with", "path that only functions from this module could set def", "request from flask_kajiki import render_template # N. B. settting i18n.gettext", "# so we test for request path that only functions", "# TODO DOCTYPE; see also render_args expected = '<p>HELLO!</p>' assert", "== '/test_i18n': return s.upper() return s i18n.gettext = gettext def", "module could set def gettext(s): if request.path == '/test_i18n': return", "all modules, # so we test for request path that", "return s i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is", "to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') #", "Translator filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE;", "with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see also", "from flask import request from flask_kajiki import render_template # N.", "gettext def test_does_translations(app): \"\"\"Callback interface is able to inject Translator", "settting i18n.gettext would affect tests from all modules, # so", "flask import request from flask_kajiki import render_template # N. B.", "would affect tests from all modules, # so we test", "from kajiki import i18n from flask import request from flask_kajiki", "that only functions from this module could set def gettext(s):", "tests from all modules, # so we test for request", "affect tests from all modules, # so we test for", "i18n.gettext = gettext def test_does_translations(app): \"\"\"Callback interface is able to", "filter\"\"\" with app.test_request_context(path='/test_i18n'): rendered = render_template('i18n.html') # TODO DOCTYPE; see", "rendered = render_template('i18n.html') # TODO DOCTYPE; see also render_args expected", "i18n.gettext would affect tests from all modules, # so we", "see also render_args expected = '<p>HELLO!</p>' assert rendered == expected", "kajiki import i18n from flask import request from flask_kajiki import", "\"\"\"Callback interface is able to inject Translator filter\"\"\" with app.test_request_context(path='/test_i18n'):", "# N. B. settting i18n.gettext would affect tests from all", "B. settting i18n.gettext would affect tests from all modules, #", "if request.path == '/test_i18n': return s.upper() return s i18n.gettext =", "i18n from flask import request from flask_kajiki import render_template #", "could set def gettext(s): if request.path == '/test_i18n': return s.upper()" ]
[ "(None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method,", "x = self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x)", "im_mask[(inds, ) + spatial_inds] = masks_chunk for i in range(N):", "== 'cpu') if threshold >= 0: masks_chunk = (masks_chunk >=", "chunk. if device.type == 'cpu': # CPU is most efficient", "GPU_MEM_LIMIT is too small; try increasing it' chunks = torch.chunk(torch.arange(N,", "rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and", "nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x):", "img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h =", "upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear',", "- y0) / (y1 - y0) * 2 - 1", "bound all boxes, and returns the results this region only.", "y1_int = img_w, img_h x0, y0, x1, y1 = torch.split(boxes,", "self.conv_logits]: if m is None: continue elif isinstance(m, CARAFEPack): m.init_weights()", "mask of shape (N, img_h, img_w) and an empty tuple.", "size) # by using the entire image to sample the", "if device.type == 'cpu': # CPU is most efficient when", "# and paste them chunk by chunk. if device.type ==", "None: x = self.upsample(x) if self.upsample_method == 'deconv': x =", "chunk size) # by using the entire image to sample", "self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg", "img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3)", "= loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg,", "region that tightly bound all boxes, and returns the results", "the image to be pasted. skip_empty (bool): Only paste masks", "mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import", "for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes,", "= len(mask_pred) # The actual implementation split the input into", "rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h", "if m is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else:", "for i in range(self.num_convs): in_channels = ( self.in_channels if i", "4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3,", "\"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is", "WARN: roi_feat_size is reserved and not used self.roi_feat_size = _pair(roi_feat_size)", "important optimization for CPU. Returns: tuple: (Tensor, tuple). The first", "[self.upsample, self.conv_logits]: if m is None: continue elif isinstance(m, CARAFEPack):", "upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs", "pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred,", "0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization", "one is the slice object. If skip_empty == False, the", "det_bboxes[:, :4] labels = det_labels if rescale: img_h, img_w =", "from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from", "2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels", "direct output of model, whose type is Tensor, while for", "# The actual implementation split the input into chunks, #", "The first item is mask tensor, the second one is", "area around the mask will be pasted. A mask of", "1, dim=1) # each is Nx1 N = masks.shape[0] img_y", "= self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None elif", "'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]},", "img_h x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) #", "- x0) * 2 - 1 # img_x, img_y have", "mask_pred (Tensor or ndarray): shape (n, #class, h, w). For", "bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold >= 0:", "will be pasted. It will return a mask of shape", "1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if", "= bboxes / scale_factor N = len(mask_pred) # The actual", "ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = (", "CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair", "= mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred,", "memory issue num_chunks = int( np.ceil(N * img_h * img_w", "GPU benefits from parallelism for larger chunks, # but may", "upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\",", "bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class, h,", "is Tensor, while for multi-scale testing, it will be converted", "if rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor, float):", "else: # for visualization and debugging masks_chunk = (masks_chunk *", "255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for i in", "self.num_convs = num_convs # WARN: roi_feat_size is reserved and not", "is the slice object. If skip_empty == False, the whole", "threshold >= 0 else torch.uint8) if not self.class_agnostic: mask_pred =", "def forward(self, x): for conv in self.convs: x = conv(x)", "img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample(", "img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <=", "HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This memory limit", "one with # skip_empty=True, so that it performs minimal number", "self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs", "F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d", "suppress warnings align_corners = (None if self.upsample_method == 'nearest' else", "= build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None if", "self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals =", "= np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if not", "be pasted. skip_empty (bool): Only paste masks within the region", "of shape (N, h', w') and its start and end", "but is faster on COCO-scale dataset. device = masks.device if", "x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1", "x0_int, y0_int = 0, 0 x1_int, y1_int = img_w, img_h", "'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_)", "Nx1 N = masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device,", "self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask']", "None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out',", "else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[]", "try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold =", "else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append(", "and its start and end coordinates in the original image", "isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device", "loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if", "== 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_)", "them one by one, # this has more operations but", "(x1 - x0) * 2 - 1 # img_x, img_y", "= torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros(", "conv in self.convs: x = conv(x) if self.upsample is not", "isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes /", "import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4", "will be converted to numpy array outside of this method.", "device = mask_pred.device cls_segms = [[] for _ in range(self.num_classes)", "3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0", "img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] =", "0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5", "not included in num_classes bboxes = det_bboxes[:, :4] labels =", "if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method", "masks acoording to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/", "would be better to # determine it based on available", "= num_convs # WARN: roi_feat_size is reserved and not used", "multi-scale testing, it will be converted to numpy array outside", "paste them chunk by chunk. if device.type == 'cpu': #", "cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks", "_pair from mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss", "boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor):", "The actual implementation split the input into chunks, # and", "outside of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels", "have shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds =", "\"\"\"Get segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor", "img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x", "loss(self, mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0) ==", "rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds =", "_pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels", "np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor", "type is Tensor, while for multi-scale testing, it will be", "img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N,", "on COCO-scale dataset. device = masks.device if skip_empty: x0_int, y0_int", "else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self,", "self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred =", "m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for", "else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w", "for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds],", "if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32)", "from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner", "'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs =", "( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits =", "loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask =", "the slice object. If skip_empty == False, the whole image", "= torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False)", "F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int,", "pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [", "roi_feat_size is reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels", "mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] =", "= mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms", "each is Nx1 N = masks.shape[0] img_y = torch.arange( y0_int,", "object. If skip_empty == False, the whole image will be", "and bboxes. Args: mask_pred (Tensor or ndarray): shape (n, #class,", "this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape", "x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int =", "more operations but is faster on COCO-scale dataset. device =", "testing config ori_shape: original image size Returns: list[list]: encoded masks", "# BG is not included in num_classes bboxes = det_bboxes[:,", "isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1]", "gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty:", "if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds", "res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg)", "isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0)", "1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32)", "(n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor): shape", "will be returned. \"\"\" # On GPU, paste all masks", "(img_x - x0) / (x1 - x0) * 2 -", "import torch import torch.nn as nn import torch.nn.functional as F", "pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets", "= mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def", "too small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks)", "1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg,", "= 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor)", "self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1)", "actual implementation split the input into chunks, # and paste", "shape (N, h', w') and its start and end coordinates", "type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type']", "memory limit may be too much or too little. It", "upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings", "x = conv(x) if self.upsample is not None: x =", "1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32)", "warnings align_corners = (None if self.upsample_method == 'nearest' else False)", "if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx =", "'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu =", "scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0]", "* img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks", "for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks,", "= torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int", "mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg):", "self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None)", "m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def", "whole image will be pasted. It will return a mask", "upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1", "is None: self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update(", "dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0", "* img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N),", "of model, whose type is Tensor, while for multi-scale testing,", "min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int", "img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32),", "num_chunks = int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT", "(int): Height of the image to be pasted. img_w (int):", "too much or too little. It would be better to", "if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size -", "align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else", "= None def init_weights(self): for m in [self.upsample, self.conv_logits]: if", "self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes", "mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss =", "instance masks acoording to boxes. This implementation is modified from", "img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config", "= nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels", "if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes =", "loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets,", "minimal number of # operations. num_chunks = N else: #", "x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self,", "pasted. skip_empty (bool): Only paste masks within the region that", "skip_empty (bool): Only paste masks within the region that tightly", "Only paste masks within the region that tightly bound all", "self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None,", "m in [self.upsample, self.conv_logits]: if m is None: continue elif", "bboxes = det_bboxes[:, :4] labels = det_labels if rescale: img_h,", "= torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp(", "shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original", "False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i in", "img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] *", "+ 0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) +", "(n, #class, h, w). For single-scale testing, mask_pred is the", "self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method ==", "torch.nn as nn import torch.nn.functional as F from mmcv.cnn import", "+ spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return", "in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels", "== 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu", "= masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] -", "super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [", "build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel =", ":, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks", "num_convs # WARN: roi_feat_size is reserved and not used self.roi_feat_size", "mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms =", "(N, img_h, img_w) and an empty tuple. If skip_empty ==", "chunk by chunk. if device.type == 'cpu': # CPU is", "i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1)", "sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results ]", "masks together (up to chunk size) # by using the", "Args: mask_pred (Tensor or ndarray): shape (n, #class, h, w).", "if self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if", "mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape (n,", "elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_)", "when they are pasted one by one with # skip_empty=True,", "= self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals", "return a mask of shape (N, img_h, img_w) and an", "together (up to chunk size) # by using the entire", "= mask_pred.device cls_segms = [[] for _ in range(self.num_classes) ]", "torch.nn.modules.utils import _pair from mmdet.core import mask_target from mmdet.models.builder import", "into chunks, # and paste them chunk by chunk. if", "'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif", "nn import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer", "self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for", "num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)):", "the region that tightly bound all boxes, and returns the", "\"\"\" # On GPU, paste all masks together (up to", "y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int,", "self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor", "ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack", "= 4 # TODO: This memory limit may be too", "= np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1]", "Compared to pasting them one by one, # this has", "conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg =", "mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold >=", "gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx,", "the second one is the slice object. If skip_empty ==", "range(self.num_convs): in_channels = ( self.in_channels if i == 0 else", "auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import mask_target", "None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg", "det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred", "[ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals,", "self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels = (", "(Tensor): shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg", "raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are", "torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:,", "np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h", "x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y -", "limit may be too much or too little. It would", "1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int, y1_int", "= masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def", "None: self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels,", "conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss',", "is Nx1 N = masks.shape[0] img_y = torch.arange( y0_int, y1_int,", "shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape (Tensor):", "0, 0 x1_int, y1_int = img_w, img_h x0, y0, x1,", "# Compared to pasting them one by one, # this", "det_labels if rescale: img_h, img_w = ori_shape[:2] else: if isinstance(scale_factor,", "image to sample the masks # Compared to pasting them", "gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets,", "+ 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int,", "= torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:,", "Tensor, while for multi-scale testing, it will be converted to", "torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if", "import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16,", "logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels)", "= self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels)", "is too small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device),", "only. An important optimization for CPU. Returns: tuple: (Tensor, tuple).", "0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2", "masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5", "device=device, dtype=torch.bool if threshold >= 0 else torch.uint8) if not", "0.5 img_y = (img_y - y0) / (y1 - y0)", "gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:,", "w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)):", "Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred =", "img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default", "this region only. An important optimization for CPU. Returns: tuple:", "shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x))", "masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred", "inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None,", "(Tensor): N, 1, H, W boxes (Tensor): N, 4 img_h", "they are pasted one by one with # skip_empty=True, so", "torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange(", "= 0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy", "in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict(", "if self.upsample is not None: x = self.upsample(x) if self.upsample_method", "img_w, skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk =", "= None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor,", "= torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None, :].expand(N,", "methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs", "# suppress warnings align_corners = (None if self.upsample_method == 'nearest'", "is not included in num_classes bboxes = det_bboxes[:, :4] labels", "self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample", "returned. \"\"\" # On GPU, paste all masks together (up", "- 1 # img_x, img_y have shapes (N, w), (N,", "one by one, # this has more operations but is", "tuple: (Tensor, tuple). The first item is mask tensor, the", "np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0", "be returned. \"\"\" # On GPU, paste all masks together", "0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return img_masks[:, 0], ()", "benefits from parallelism for larger chunks, # but may have", "mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT =", "dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32)", "ndarray): shape (n, #class, h, w). For single-scale testing, mask_pred", "= self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def", "y0) / (y1 - y0) * 2 - 1 img_x", "and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size", "else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return", "det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from", "shape (n, #class, h, w). For single-scale testing, mask_pred is", "num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None,", "] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred',", "roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None,", "gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds", "N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else", "implementation split the input into chunks, # and paste them", "np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor,", "# for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8)", "for larger chunks, # but may have memory issue num_chunks", "rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size Returns:", "the masks # Compared to pasting them one by one,", "https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes (Tensor):", "img_y[inds] = 0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1))", "skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int", "implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1,", "will be pasted. A mask of shape (N, h', w')", "# but may have memory issue num_chunks = int( np.ceil(N", "self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None", "for multi-scale testing, it will be converted to numpy array", "H, W boxes (Tensor): N, 4 img_h (int): Height of", "slice object. If skip_empty == False, the whole image will", "return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance", "elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample", "This memory limit may be too much or too little.", "has more operations but is faster on COCO-scale dataset. device", "y1 = torch.split(boxes, 1, dim=1) # each is Nx1 N", "= torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y))", "acoording to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args:", "by using the entire image to sample the masks #", "torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y", "# operations. num_chunks = N else: # GPU benefits from", "img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid =", "build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from", "init_weights(self): for m in [self.upsample, self.conv_logits]: if m is None:", "is not None: x = self.upsample(x) if self.upsample_method == 'deconv':", "= torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 img_x =", "@force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss = dict()", "self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None elif self.upsample_method", "import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import", "'cpu') if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool)", "boxes, and returns the results this region only. An important", "is most efficient when they are pasted one by one", "loss = dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum()", "sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in sampling_results]", "chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type", "labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes,", "scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale =", "'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def", "to be pasted. img_w (int): Width of the image to", "img_w) and an empty tuple. If skip_empty == True, only", "tuple. If skip_empty == True, only area around the mask", "in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in sampling_results", "N else: # GPU benefits from parallelism for larger chunks,", "sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets", "img_w, img_h x0, y0, x1, y1 = torch.split(boxes, 1, dim=1)", "is mask tensor, the second one is the slice object.", "in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample =", "# GPU benefits from parallelism for larger chunks, # but", "res.pos_assigned_gt_inds for res in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds,", "conv(x) if self.upsample is not None: x = self.upsample(x) if", "N), 'Default GPU_MEM_LIMIT is too small; try increasing it' chunks", "import _pair from mmdet.core import mask_target from mmdet.models.builder import HEADS,", "upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method", "channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners", "converted to numpy array outside of this method. det_bboxes (Tensor):", "bboxes = bboxes / scale_factor N = len(mask_pred) # The", "'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted", "have memory issue num_chunks = int( np.ceil(N * img_h *", "and returns the results this region only. An important optimization", "# by using the entire image to sample the masks", "the results this region only. An important optimization for CPU.", "# each is Nx1 N = masks.shape[0] img_y = torch.arange(", "modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W", "= (img_y - y0) / (y1 - y0) * 2", "2 - 1 # img_x, img_y have shapes (N, w),", "self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels", "from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO:", "conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor',", "masks from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray):", ") rcnn_test_cfg (dict): rcnn testing config ori_shape: original image size", "image to be pasted. img_w (int): Width of the image", "If skip_empty == True, only area around the mask will", "shape (n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict):", "skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This implementation is", "threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device,", "__init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2),", "nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv in", "be converted to numpy array outside of this method. det_bboxes", "the input into chunks, # and paste them chunk by", "im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold", "if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels,", "if threshold >= 0 else torch.uint8) if not self.class_agnostic: mask_pred", "= torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y =", "img_y = (img_y - y0) / (y1 - y0) *", "0 else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:,", "self.convs: x = conv(x) if self.upsample is not None: x", "may have memory issue num_chunks = int( np.ceil(N * img_h", "img_y have shapes (N, w), (N, h) if torch.isinf(img_x).any(): inds", "> 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is", "= self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg", "padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs >", "mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets,", "issue num_chunks = int( np.ceil(N * img_h * img_w *", "mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for", "self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return", "= int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT /", "threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk = (masks_chunk", "= [res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds", "output of model, whose type is Tensor, while for multi-scale", "list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid()", "- 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1,", "cls_segms = [[] for _ in range(self.num_classes) ] # BG", "self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs):", "to sample the masks # Compared to pasting them one", "force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import mask_target from", "== 'cpu': # CPU is most efficient when they are", "class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80,", "@HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256,", "= class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled =", ":].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1))", "the whole image will be pasted. It will return a", "of this method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor):", "image will be pasted. It will return a mask of", "are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs #", "masks (Tensor): N, 1, H, W boxes (Tensor): N, 4", "img_x = torch.arange( x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 img_y", "the image to be pasted. img_w (int): Width of the", "tightly bound all boxes, and returns the results this region", "self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor)", "1024**3 # 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def", "in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w,", "Args: masks (Tensor): N, 1, H, W boxes (Tensor): N,", "upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample = None", "mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 #", "of the image to be pasted. skip_empty (bool): Only paste", "COCO-scale dataset. device = masks.device if skip_empty: x0_int, y0_int =", "testing, mask_pred is the direct output of model, whose type", "dtype=torch.bool if threshold >= 0 else torch.uint8) if not self.class_agnostic:", "upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else in_channels)", "= 1 if self.class_agnostic else self.num_classes logits_in_channel = ( self.conv_out_channels", "shape (N, img_h, img_w) and an empty tuple. If skip_empty", "= det_labels if rescale: img_h, img_w = ori_shape[:2] else: if", "is faster on COCO-scale dataset. device = masks.device if skip_empty:", "mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core", "= conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask =", "[[] for _ in range(self.num_classes) ] # BG is not", "masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1,", "operations. num_chunks = N else: # GPU benefits from parallelism", "import torch.nn as nn import torch.nn.functional as F from mmcv.cnn", "in_channels = ( self.in_channels if i == 0 else self.conv_out_channels)", "' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs", "if self.upsample_method == 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x)", "input into chunks, # and paste them chunk by chunk.", "torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N,", "= dict() if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() *", "= mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk, spatial_inds", "img_x, img_y have shapes (N, w), (N, h) if torch.isinf(img_x).any():", "img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return img_masks[:, 0],", "norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList()", "N, 1, H, W boxes (Tensor): N, 4 img_h (int):", "det_labels (Tensor): shape (n, ) img_shape (Tensor): shape (3, )", "- 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding,", "in range(self.num_classes) ] # BG is not included in num_classes", "is the direct output of model, whose type is Tensor,", "torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N", "numpy array outside of this method. det_bboxes (Tensor): shape (n,", "BG is not included in num_classes bboxes = det_bboxes[:, :4]", "else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True)", "h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if", "= build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel", "labels): loss = dict() if mask_pred.size(0) == 0: loss_mask =", "inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h,", "0 gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy =", "within the region that tightly bound all boxes, and returns", "= [[] for _ in range(self.num_classes) ] # BG is", "self.conv_logits = Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs =", "of # operations. num_chunks = N else: # GPU benefits", "self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels =", "None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor)", "else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels", "self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits = Conv2d(logits_in_channel,", "scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and bboxes. Args:", "labels = det_labels if rescale: img_h, img_w = ori_shape[:2] else:", "h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32)", "= torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >=", "return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels): loss", "scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N =", "int( np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT))", "get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res in", "in range(self.num_convs): in_channels = ( self.in_channels if i == 0", "to numpy array outside of this method. det_bboxes (Tensor): shape", "(self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size,", "rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if", "A mask of shape (N, h', w') and its start", "Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32", "mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self,", "img_w = ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0]", "for visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds,", "self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs", "that tightly bound all boxes, and returns the results this", "img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This implementation", "pasted. A mask of shape (N, h', w') and its", ")) def loss(self, mask_pred, mask_targets, labels): loss = dict() if", "[ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid", "as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import", "self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if", "img_h, img_w) and an empty tuple. If skip_empty == True,", "+ 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1,", "if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred)", "nn.ModuleList() for i in range(self.num_convs): in_channels = ( self.in_channels if", "_do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if threshold", "= (img_x - x0) / (x1 - x0) * 2", "mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device = mask_pred.device", "device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int, device=device,", "small; try increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold", "FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False,", "while for multi-scale testing, it will be converted to numpy", "_do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to", "available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit", "parallelism for larger chunks, # but may have memory issue", "self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m", "split the input into chunks, # and paste them chunk", "det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for _ in", "mask tensor, the second one is the slice object. If", "self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample =", "in num_classes bboxes = det_bboxes[:, :4] labels = det_labels if", "be pasted. img_w (int): Width of the image to be", "torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int =", "# img_x, img_y have shapes (N, w), (N, h) if", "if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else:", "(N, w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds]", "None def init_weights(self): for m in [self.upsample, self.conv_logits]: if m", "import numpy as np import torch import torch.nn as nn", "self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method", "= build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample", "(Tensor, tuple). The first item is mask tensor, the second", "in the original image will be returned. \"\"\" # On", "sample the masks # Compared to pasting them one by", "labels][:, None] for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask(", "of shape (N, img_h, img_w) and an empty tuple. If", "a mask of shape (N, img_h, img_w) and an empty", "= F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0],", "forward(self, x): for conv in self.convs: x = conv(x) if", "(int): Width of the image to be pasted. skip_empty (bool):", "around the mask will be pasted. A mask of shape", "scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners =", "it will be converted to numpy array outside of this", "that it performs minimal number of # operations. num_chunks =", "1, H, W boxes (Tensor): N, 4 img_h (int): Height", "<reponame>jstzwjr/mmdetection<gh_stars>1-10 import numpy as np import torch import torch.nn as", "= nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m in", "GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit @HEADS.register_module() class", "mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe", "* w_scale.item()).astype( np.int32) scale_factor = 1.0 if not isinstance(scale_factor, (float,", "\"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN:", "mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', ))", "{self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", ' '\"carafe\"')", "'Default GPU_MEM_LIMIT is too small; try increasing it' chunks =", "1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4,", "from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from", "paste all masks together (up to chunk size) # by", "start and end coordinates in the original image will be", "x0) * 2 - 1 # img_x, img_y have shapes", "inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds =", "model, whose type is Tensor, while for multi-scale testing, it", "not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes", "it based on available resources. GPU_MEM_LIMIT = 1024**3 # 1", "grid = torch.stack([gx, gy], dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid,", "may be too much or too little. It would be", "torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx = img_x[:, None, :].expand(N, img_y.size(1),", "h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor =", "boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes.", "else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask", "will return a mask of shape (N, img_h, img_w) and", "skip_empty == True, only area around the mask will be", "single-scale testing, mask_pred is the direct output of model, whose", "all boxes, and returns the results this region only. An", "range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True):", "class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead,", "'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, '", "else: # suppress warnings align_corners = (None if self.upsample_method ==", "import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import", "= num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg =", "config ori_shape: original image size Returns: list[list]: encoded masks \"\"\"", "def loss(self, mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0)", "= det_bboxes.new_tensor(mask_pred) device = mask_pred.device cls_segms = [[] for _", "one, # this has more operations but is faster on", "else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] *", "* 2 - 1 # img_x, img_y have shapes (N,", "align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int))", "but may have memory issue num_chunks = int( np.ceil(N *", "w_scale, h_scale = scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype(", "mask_targets, labels): loss = dict() if mask_pred.size(0) == 0: loss_mask", "device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h,", "loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels,", "torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds", "(num_chunks <= N), 'Default GPU_MEM_LIMIT is too small; try increasing", "self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv' else", "0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else:", "region only. An important optimization for CPU. Returns: tuple: (Tensor,", "this has more operations but is faster on COCO-scale dataset.", "self.upsample_method is None: self.upsample = None elif self.upsample_method == 'deconv':", "== 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: #", "conv_cfg=conv_cfg, norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0", "np.ceil(N * img_h * img_w * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert", "'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample method", "upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__()", "BYTES_PER_FLOAT = 4 # TODO: This memory limit may be", "[res.pos_bboxes for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for", "self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred,", "an empty tuple. If skip_empty == True, only area around", "rescale): \"\"\"Get segmentation masks from mask_pred and bboxes. Args: mask_pred", "for res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res", "mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils", "torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops", "mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self, mask_pred,", "mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv", "TODO: This memory limit may be too much or too", "1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for", "scale_factor N = len(mask_pred) # The actual implementation split the", "For single-scale testing, mask_pred is the direct output of model,", "y0_int = 0, 0 x1_int, y1_int = img_w, img_h x0,", "1 # img_x, img_y have shapes (N, w), (N, h)", "loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss", "N, 4 img_h (int): Height of the image to be", "It would be better to # determine it based on", "from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H, W boxes", "/ scale_factor N = len(mask_pred) # The actual implementation split", "masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int),", "its start and end coordinates in the original image will", "loss_mask return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape,", "with # skip_empty=True, so that it performs minimal number of", "as nn import torch.nn.functional as F from mmcv.cnn import ConvModule,", "determine it based on available resources. GPU_MEM_LIMIT = 1024**3 #", "to be pasted. skip_empty (bool): Only paste masks within the", "only area around the mask will be pasted. A mask", "4 img_h (int): Height of the image to be pasted.", "= img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy],", "return loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor,", "(y1 - y0) * 2 - 1 img_x = (img_x", "4 # TODO: This memory limit may be too much", "GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14,", "one by one with # skip_empty=True, so that it performs", "from parallelism for larger chunks, # but may have memory", "to chunk size) # by using the entire image to", "in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError(", "scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w =", "second one is the slice object. If skip_empty == False,", "self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else:", "True, only area around the mask will be pasted. A", "If skip_empty == False, the whole image will be pasted.", "if threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else:", "max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else:", "(n, ) img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn", "them chunk by chunk. if device.type == 'cpu': # CPU", "resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory limit @HEADS.register_module()", "scale_factor = 1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor =", "= N else: # GPU benefits from parallelism for larger", "optimization for CPU. Returns: tuple: (Tensor, tuple). The first item", "# this has more operations but is faster on COCO-scale", "- x0) / (x1 - x0) * 2 - 1", "/ GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too", "= img_w, img_h x0, y0, x1, y1 = torch.split(boxes, 1,", "ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\",", "res in sampling_results] pos_assigned_gt_inds = [ res.pos_assigned_gt_inds for res in", "ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32)", "N = masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32)", "img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording to boxes. This", "det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, )", "self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask", "False, the whole image will be pasted. It will return", "not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds in", "= [ res.pos_assigned_gt_inds for res in sampling_results ] mask_targets =", "skip_empty=True, so that it performs minimal number of # operations.", "masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks,", "i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h,", "Width of the image to be pasted. skip_empty (bool): Only", "increasing it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary", "else self.num_classes logits_in_channel = ( self.conv_out_channels if self.upsample_method == 'deconv'", "= ( self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_", "range(self.num_classes) ] # BG is not included in num_classes bboxes", "(bool): Only paste masks within the region that tightly bound", "y1_int, device=device, dtype=torch.float32) + 0.5 img_x = torch.arange( x0_int, x1_int,", "loss def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale):", "in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type')", "it' chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask", "efficient when they are pasted one by one with #", "in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w,", "self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic =", "to boxes. This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks", "@auto_fp16() def forward(self, x): for conv in self.convs: x =", "for CPU. Returns: tuple: (Tensor, tuple). The first item is", "i in range(self.num_convs): in_channels = ( self.in_channels if i ==", "* 0 else: if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels))", "(Tensor or ndarray): shape (n, #class, h, w). For single-scale", "Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def", "performs minimal number of # operations. num_chunks = N else:", "chunks, # but may have memory issue num_chunks = int(", "by chunk. if device.type == 'cpu': # CPU is most", "mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks", "torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for", "h', w') and its start and end coordinates in the", "x0) / (x1 - x0) * 2 - 1 #", "self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled", "Returns: tuple: (Tensor, tuple). The first item is mask tensor,", "== 0 else self.conv_out_channels) padding = (self.conv_kernel_size - 1) //", ") img_shape (Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing", "use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not", "if self.class_agnostic: loss_mask = self.loss_mask(mask_pred, mask_targets, torch.zeros_like(labels)) else: loss_mask =", "(N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0", "= self.upsample(x) if self.upsample_method == 'deconv': x = self.relu(x) mask_pred", "y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp(", "threshold >= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: #", "mask_pred = mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk,", ">= 0: masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for", "operations but is faster on COCO-scale dataset. device = masks.device", "little. It would be better to # determine it based", ">= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk =", "masks within the region that tightly bound all boxes, and", "# determine it based on available resources. GPU_MEM_LIMIT = 1024**3", "* h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor", "norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy()", "self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask return loss def get_seg_masks(self,", "self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]:", "in_channels=upsample_in_channels, out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method ==", "= 1024**3 # 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module):", "img_h (int): Height of the image to be pasted. img_w", "size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred", "0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0 gx", "device = masks.device if skip_empty: x0_int, y0_int = torch.clamp( boxes.min(dim=0).values.floor()[:2]", "= img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :,", "of the image to be pasted. img_w (int): Width of", "img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) grid", "norm_cfg=norm_cfg)) upsample_in_channels = ( self.conv_out_channels if self.num_convs > 0 else", "= conv(x) if self.upsample is not None: x = self.upsample(x)", "tensor, the second one is the slice object. If skip_empty", "] # BG is not included in num_classes bboxes =", "= det_bboxes[:, :4] labels = det_labels if rescale: img_h, img_w", "BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is", "W boxes (Tensor): N, 4 img_h (int): Height of the", "0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None:", "image will be returned. \"\"\" # On GPU, paste all", "faster on COCO-scale dataset. device = masks.device if skip_empty: x0_int,", "mask_pred.device cls_segms = [[] for _ in range(self.num_classes) ] #", "it performs minimal number of # operations. num_chunks = N", "if self.upsample_method is None: self.upsample = None elif self.upsample_method ==", "and paste them chunk by chunk. if device.type == 'cpu':", "torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0", "masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] =", "torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds]", "None] for inds in chunks: masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds],", "= 0, 0 x1_int, y1_int = img_w, img_h x0, y0,", "#class, h, w). For single-scale testing, mask_pred is the direct", "else: # GPU benefits from parallelism for larger chunks, #", "* scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale", "This implementation is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N,", "= ( self.in_channels if i == 0 else self.conv_out_channels) padding", "self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None] for inds in chunks:", "to # determine it based on available resources. GPU_MEM_LIMIT =", "based on available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB", "using the entire image to sample the masks # Compared", "be better to # determine it based on available resources.", "GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too small;", "mask_pred[range(N), labels][:, None] for inds in chunks: masks_chunk, spatial_inds =", "build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels =", "not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size =", "bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N = len(mask_pred) #", "torch.clamp( boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil()", "(img_y - y0) / (y1 - y0) * 2 -", "def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste instance masks acoording", "(masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for", "img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8) if", "padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels,", "'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) else: # suppress", "1.0 if not isinstance(scale_factor, (float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes", "bboxes / scale_factor N = len(mask_pred) # The actual implementation", "original image will be returned. \"\"\" # On GPU, paste", "(up to chunk size) # by using the entire image", "self.debug_imgs = None def init_weights(self): for m in [self.upsample, self.conv_logits]:", "device.type == 'cpu': # CPU is most efficient when they", "self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results, gt_masks,", "torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:,", "is modified from https://github.com/facebookresearch/detectron2/ Args: masks (Tensor): N, 1, H,", "def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for res", "align_corners = (None if self.upsample_method == 'nearest' else False) upsample_cfg_.update(", "larger chunks, # but may have memory issue num_chunks =", "mask of shape (N, h', w') and its start and", "elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias,", "out_channels=self.conv_out_channels, kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe':", "boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil()", "from mask_pred and bboxes. Args: mask_pred (Tensor or ndarray): shape", "method. det_bboxes (Tensor): shape (n, 4/5) det_labels (Tensor): shape (n,", "to pasting them one by one, # this has more", "the original image will be returned. \"\"\" # On GPU,", "= in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method =", "if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners)", "image size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor):", "boxes (Tensor): N, 4 img_h (int): Height of the image", "continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu')", "if mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0 else:", "get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get segmentation", "skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk = (masks_chunk", "= Conv2d(logits_in_channel, out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None", "= ( self.conv_out_channels if self.upsample_method == 'deconv' else upsample_in_channels) self.conv_logits", "# TODO: This memory limit may be too much or", "self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_ = self.upsample_cfg.copy()", "2 - 1 img_x = (img_x - x0) / (x1", "self.upsample is not None: x = self.upsample(x) if self.upsample_method ==", "def get_seg_masks(self, mask_pred, det_bboxes, det_labels, rcnn_test_cfg, ori_shape, scale_factor, rescale): \"\"\"Get", "= (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging", "better to # determine it based on available resources. GPU_MEM_LIMIT", "= False self.loss_mask = build_loss(loss_mask) self.convs = nn.ModuleList() for i", "img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32)", "included in num_classes bboxes = det_bboxes[:, :4] labels = det_labels", "torch.split(boxes, 1, dim=1) # each is Nx1 N = masks.shape[0]", "not None: x = self.upsample(x) if self.upsample_method == 'deconv': x", "h, w). For single-scale testing, mask_pred is the direct output", "rcnn testing config ori_shape: original image size Returns: list[list]: encoded", "in sampling_results ] mask_targets = mask_target(pos_proposals, pos_assigned_gt_inds, gt_masks, rcnn_train_cfg) return", "scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1]", "self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic", "CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight, mode='fan_out', nonlinearity='relu') nn.init.constant_(m.bias, 0) @auto_fp16()", "for conv in self.convs: x = conv(x) if self.upsample is", "is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_( m.weight,", "whose type is Tensor, while for multi-scale testing, it will", "(3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape: original image", "by one with # skip_empty=True, so that it performs minimal", "0 x1_int, y1_int = img_w, img_h x0, y0, x1, y1", "x1_int = torch.clamp( boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int =", "conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes =", "self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method", "= self.relu(x) mask_pred = self.conv_logits(x) return mask_pred def get_targets(self, sampling_results,", "number of # operations. num_chunks = N else: # GPU", "num_classes bboxes = det_bboxes[:, :4] labels = det_labels if rescale:", "// 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels, self.conv_kernel_size, padding=padding, conv_cfg=conv_cfg, norm_cfg=norm_cfg))", ":4] labels = det_labels if rescale: img_h, img_w = ori_shape[:2]", "scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg", "It will return a mask of shape (N, img_h, img_w)", "x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each", "= masks.shape[0] img_y = torch.arange( y0_int, y1_int, device=device, dtype=torch.float32) +", "dtype=torch.float32) + 0.5 img_y = (img_y - y0) / (y1", "img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32) scale_factor = 1.0 if", "rcnn_train_cfg) return mask_targets @force_fp32(apply_to=('mask_pred', )) def loss(self, mask_pred, mask_targets, labels):", "grid, align_corners=False) if skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int,", "the mask will be pasted. A mask of shape (N,", "and end coordinates in the original image will be returned.", "testing, it will be converted to numpy array outside of", "or too little. It would be better to # determine", "f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\",", "build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels, scale_factor=self.scale_factor) self.upsample =", "== 'deconv': x = self.relu(x) mask_pred = self.conv_logits(x) return mask_pred", "N = len(mask_pred) # The actual implementation split the input", "'cpu': # CPU is most efficient when they are pasted", "- 1 img_x = (img_x - x0) / (x1 -", "else in_channels) upsample_cfg_ = self.upsample_cfg.copy() if self.upsample_method is None: self.upsample", "results this region only. An important optimization for CPU. Returns:", "not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise", "nn.init.constant_(m.bias, 0) @auto_fp16() def forward(self, x): for conv in self.convs:", "much or too little. It would be better to #", "# CPU is most efficient when they are pasted one", "= _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu') if", "= (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule( in_channels, self.conv_out_channels,", "(Tensor): N, 4 img_h (int): Height of the image to", "y0) * 2 - 1 img_x = (img_x - x0)", "mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This", "num_classes self.class_agnostic = class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg", "dataset. device = masks.device if skip_empty: x0_int, y0_int = torch.clamp(", "_ in range(self.num_classes) ] # BG is not included in", "mask_pred is the direct output of model, whose type is", "img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0],", "= norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask) self.convs =", "and an empty tuple. If skip_empty == True, only area", "end coordinates in the original image will be returned. \"\"\"", "entire image to sample the masks # Compared to pasting", "- y0) * 2 - 1 img_x = (img_x -", "in [self.upsample, self.conv_logits]: if m is None: continue elif isinstance(m,", "stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update( channels=upsample_in_channels,", "= _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size self.conv_out_channels =", "y1_int = torch.clamp( boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int,", "item is mask tensor, the second one is the slice", "import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from", "1 img_x = (img_x - x0) / (x1 - x0)", "be pasted. It will return a mask of shape (N,", "= conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes", "* BYTES_PER_FLOAT / GPU_MEM_LIMIT)) assert (num_chunks <= N), 'Default GPU_MEM_LIMIT", "\"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred =", "len(mask_pred) # The actual implementation split the input into chunks,", "limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3,", "np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype( np.int32)", "boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0,", "original image size Returns: list[list]: encoded masks \"\"\" if isinstance(mask_pred,", "x): for conv in self.convs: x = conv(x) if self.upsample", "None].expand(N, img_y.size(1), img_x.size(1)) grid = torch.stack([gx, gy], dim=3) img_masks =", "0: loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic: loss_mask", "<= N), 'Default GPU_MEM_LIMIT is too small; try increasing it'", "== False, the whole image will be pasted. It will", "image to be pasted. skip_empty (bool): Only paste masks within", "all masks together (up to chunk size) # by using", "array outside of this method. det_bboxes (Tensor): shape (n, 4/5)", "from torch.nn.modules.utils import _pair from mmdet.core import mask_target from mmdet.models.builder", "self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic = class_agnostic self.conv_cfg =", "be too much or too little. It would be better", "/ (y1 - y0) * 2 - 1 img_x =", "coordinates in the original image will be returned. \"\"\" #", "mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes for", "from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from", "float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] *", "loss_weight=1.0)): super(FCNMaskHead, self).__init__() self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in", "( self.conv_out_channels if self.num_convs > 0 else in_channels) upsample_cfg_ =", "segmentation masks from mask_pred and bboxes. Args: mask_pred (Tensor or", "self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic else self.num_classes", "device=device, dtype=torch.float32) + 0.5 img_y = (img_y - y0) /", "def init_weights(self): for m in [self.upsample, self.conv_logits]: if m is", "img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return img_masks[:,", "too little. It would be better to # determine it", "used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels self.conv_kernel_size = conv_kernel_size", "out_channels, 1) self.relu = nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self):", "chunks = torch.chunk(torch.arange(N, device=device), num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask =", "else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N), labels][:, None]", "debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds]", "self.conv_out_channels) padding = (self.conv_kernel_size - 1) // 2 self.convs.append( ConvModule(", "numpy as np import torch import torch.nn as nn import", "pasting them one by one, # this has more operations", "boxes.min(dim=0).values.floor()[:2] - 1, min=0).to(dtype=torch.int32) x1_int = torch.clamp( boxes[:, 2].max().ceil() +", "2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) y1_int = torch.clamp( boxes[:, 3].max().ceil() +", "max=img_h).to(dtype=torch.int32) else: x0_int, y0_int = 0, 0 x1_int, y1_int =", "= self.upsample_cfg.get('type') self.scale_factor = self.upsample_cfg.pop('scale_factor', None) self.num_classes = num_classes self.class_agnostic", "ori_shape, scale_factor, rescale): \"\"\"Get segmentation masks from mask_pred and bboxes.", "(Tensor): shape (n, 4/5) det_labels (Tensor): shape (n, ) img_shape", "An important optimization for CPU. Returns: tuple: (Tensor, tuple). The", "so that it performs minimal number of # operations. num_chunks", "method {self.upsample_cfg[\"type\"]}, ' 'accepted methods are \"deconv\", \"nearest\", \"bilinear\", '", "are pasted one by one with # skip_empty=True, so that", "img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8)", "returns the results this region only. An important optimization for", "as np import torch import torch.nn as nn import torch.nn.functional", "reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels = in_channels", "w). For single-scale testing, mask_pred is the direct output of", "w), (N, h) if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] =", "the direct output of model, whose type is Tensor, while", "most efficient when they are pasted one by one with", "masks # Compared to pasting them one by one, #", "assert (num_chunks <= N), 'Default GPU_MEM_LIMIT is too small; try", "encoded masks \"\"\" if isinstance(mask_pred, torch.Tensor): mask_pred = mask_pred.sigmoid() else:", "False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels =", "torch import torch.nn as nn import torch.nn.functional as F from", "= np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else:", "memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256,", "kernel_size=self.scale_factor, stride=self.scale_factor) self.upsample = build_upsample_layer(upsample_cfg_) elif self.upsample_method == 'carafe': upsample_cfg_.update(", "num_chunks) threshold = rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w,", "return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return img_masks[:,", "'\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is reserved and", "self.upsample_cfg = upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv',", "pasted. It will return a mask of shape (N, img_h,", "nn.ReLU(inplace=True) self.debug_imgs = None def init_weights(self): for m in [self.upsample,", "= np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w = np.round(ori_shape[1] * w_scale.item()).astype(", "# On GPU, paste all masks together (up to chunk", "= (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk", "else: x0_int, y0_int = 0, 0 x1_int, y1_int = img_w,", "\"nearest\", \"bilinear\", ' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size", "num_chunks = N else: # GPU benefits from parallelism for", "spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type == 'cpu')", "= ori_shape[:2] else: if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] *", "if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest', 'bilinear', 'carafe'", "CPU is most efficient when they are pasted one by", "or ndarray): shape (n, #class, h, w). For single-scale testing,", "dim=1) # each is Nx1 N = masks.shape[0] img_y =", "def __init__(self, num_convs=4, roi_feat_size=14, in_channels=256, conv_kernel_size=3, conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv',", "in self.convs: x = conv(x) if self.upsample is not None:", "* 255).to(dtype=torch.uint8) im_mask[(inds, ) + spatial_inds] = masks_chunk for i", "y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is", "torch.Tensor): mask_pred = mask_pred.sigmoid() else: mask_pred = det_bboxes.new_tensor(mask_pred) device =", "scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if", "pasted. img_w (int): Width of the image to be pasted.", "img_w (int): Width of the image to be pasted. skip_empty", "mode=self.upsample_method, align_corners=align_corners) self.upsample = build_upsample_layer(upsample_cfg_) out_channels = 1 if self.class_agnostic", "== 0: loss_mask = mask_pred.sum() * 0 else: if self.class_agnostic:", "visualization and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, )", "paste masks within the region that tightly bound all boxes,", "CPU. Returns: tuple: (Tensor, tuple). The first item is mask", "cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms def _do_paste_mask(masks, boxes, img_h, img_w, skip_empty=True): \"\"\"Paste", "(masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and debugging masks_chunk", "]: raise ValueError( f'Invalid upsample method {self.upsample_cfg[\"type\"]}, ' 'accepted methods", "(N, h', w') and its start and end coordinates in", "for m in [self.upsample, self.conv_logits]: if m is None: continue", "None, 'deconv', 'nearest', 'bilinear', 'carafe' ]: raise ValueError( f'Invalid upsample", ") + spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy())", "GPU, paste all masks together (up to chunk size) #", "import auto_fp16, force_fp32 from torch.nn.modules.utils import _pair from mmdet.core import", "the entire image to sample the masks # Compared to", "from mmdet.core import mask_target from mmdet.models.builder import HEADS, build_loss BYTES_PER_FLOAT", "* scale_factor).astype(np.int32) else: w_scale, h_scale = scale_factor[0], scale_factor[1] img_h =", "chunks, # and paste them chunk by chunk. if device.type", "Height of the image to be pasted. img_w (int): Width", "skip_empty == False, the whole image will be pasted. It", "w') and its start and end coordinates in the original", "by one, # this has more operations but is faster", "x1_int, y1_int = img_w, img_h x0, y0, x1, y1 =", "img_x = (img_x - x0) / (x1 - x0) *", "if torch.isinf(img_x).any(): inds = torch.where(torch.isinf(img_x)) img_x[inds] = 0 if torch.isinf(img_y).any():", "(Tensor): shape (3, ) rcnn_test_cfg (dict): rcnn testing config ori_shape:", "(dict): rcnn testing config ori_shape: original image size Returns: list[list]:", "# 1 GB memory limit @HEADS.register_module() class FCNMaskHead(nn.Module): def __init__(self,", "and debugging masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) im_mask[(inds, ) +", "be pasted. A mask of shape (N, h', w') and", "= 0 if torch.isinf(img_y).any(): inds = torch.where(torch.isinf(img_y)) img_y[inds] = 0", "masks_chunk, spatial_inds = _do_paste_mask( mask_pred[inds], bboxes[inds], img_h, img_w, skip_empty=device.type ==", "= upsample_cfg.copy() if self.upsample_cfg['type'] not in [ None, 'deconv', 'nearest',", "img_h, img_w, skip_empty=device.type == 'cpu') if threshold >= 0: masks_chunk", "conv_out_channels=256, num_classes=80, class_agnostic=False, upsample_cfg=dict(type='deconv', scale_factor=2), conv_cfg=None, norm_cfg=None, loss_mask=dict( type='CrossEntropyLoss', use_mask=True,", "mask will be pasted. A mask of shape (N, h',", "On GPU, paste all masks together (up to chunk size)", "torch.zeros_like(labels)) else: loss_mask = self.loss_mask(mask_pred, mask_targets, labels) loss['loss_mask'] = loss_mask", "= scale_factor[0], scale_factor[1] img_h = np.round(ori_shape[0] * h_scale.item()).astype( np.int32) img_w", "# WARN: roi_feat_size is reserved and not used self.roi_feat_size =", "self.upsample = None elif self.upsample_method == 'deconv': upsample_cfg_.update( in_channels=upsample_in_channels, out_channels=self.conv_out_channels,", "first item is mask tensor, the second one is the", "= torch.split(boxes, 1, dim=1) # each is Nx1 N =", "on available resources. GPU_MEM_LIMIT = 1024**3 # 1 GB memory", "if isinstance(scale_factor, float): img_h = np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w =", "spatial_inds] = masks_chunk for i in range(N): cls_segms[labels[i]].append(im_mask[i].cpu().numpy()) return cls_segms", "* 2 - 1 img_x = (img_x - x0) /", "for _ in range(self.num_classes) ] # BG is not included", "( self.in_channels if i == 0 else self.conv_out_channels) padding =", "x1_int, device=device, dtype=torch.float32) + 0.5 img_y = (img_y - y0)", "+ 0.5 img_y = (img_y - y0) / (y1 -", "import HEADS, build_loss BYTES_PER_FLOAT = 4 # TODO: This memory", "class_agnostic self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False", "' '\"carafe\"') self.num_convs = num_convs # WARN: roi_feat_size is reserved", "= build_loss(loss_mask) self.convs = nn.ModuleList() for i in range(self.num_convs): in_channels", "np import torch import torch.nn as nn import torch.nn.functional as", "m is None: continue elif isinstance(m, CARAFEPack): m.init_weights() else: nn.init.kaiming_normal_(", "mask_pred.size(0) == 0: loss_mask = mask_pred.sum() * 0 else: if", "= conv_kernel_size self.conv_out_channels = conv_out_channels self.upsample_method = self.upsample_cfg.get('type') self.scale_factor =", "tuple). The first item is mask tensor, the second one", "empty tuple. If skip_empty == True, only area around the", "/ (x1 - x0) * 2 - 1 # img_x,", "(float, torch.Tensor)): scale_factor = bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor", "ori_shape: original image size Returns: list[list]: encoded masks \"\"\" if", "= rcnn_test_cfg.mask_thr_binary im_mask = torch.zeros( N, img_h, img_w, device=device, dtype=torch.bool", "= (None if self.upsample_method == 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor,", "# skip_empty=True, so that it performs minimal number of #", "None, :].expand(N, img_y.size(1), img_x.size(1)) gy = img_y[:, :, None].expand(N, img_y.size(1),", "pasted one by one with # skip_empty=True, so that it", ">= 0 else torch.uint8) if not self.class_agnostic: mask_pred = mask_pred[range(N),", "== True, only area around the mask will be pasted.", "mask_pred, mask_targets, labels): loss = dict() if mask_pred.size(0) == 0:", "dim=3) img_masks = F.grid_sample( masks.to(dtype=torch.float32), grid, align_corners=False) if skip_empty: return", "return mask_pred def get_targets(self, sampling_results, gt_masks, rcnn_train_cfg): pos_proposals = [res.pos_bboxes", "= bboxes.new_tensor(scale_factor) bboxes = bboxes / scale_factor N = len(mask_pred)", "build_loss BYTES_PER_FLOAT = 4 # TODO: This memory limit may", "out_channels = 1 if self.class_agnostic else self.num_classes logits_in_channel = (", "masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) else: # for visualization and", "\"\"\"Paste instance masks acoording to boxes. This implementation is modified", "is reserved and not used self.roi_feat_size = _pair(roi_feat_size) self.in_channels =", "self.in_channels if i == 0 else self.conv_out_channels) padding = (self.conv_kernel_size", "np.round(ori_shape[0] * scale_factor).astype(np.int32) img_w = np.round(ori_shape[1] * scale_factor).astype(np.int32) else: w_scale,", "skip_empty: return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) else: return", "0) @auto_fp16() def forward(self, x): for conv in self.convs: x", "== 'nearest' else False) upsample_cfg_.update( scale_factor=self.scale_factor, mode=self.upsample_method, align_corners=align_corners) self.upsample =", "build_upsample_layer(upsample_cfg_) else: # suppress warnings align_corners = (None if self.upsample_method", "conv_cfg self.norm_cfg = norm_cfg self.fp16_enabled = False self.loss_mask = build_loss(loss_mask)" ]
[ "= \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type =", "False # #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh", "0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False", "cfg = Config() #params for text detector cfg.det_algorithm = \"DB\"", "cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt = False return", "from __future__ import absolute_import from __future__ import division from __future__", "import print_function class Config(object): pass def read_params(): cfg = Config()", "detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960", "= 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation =", "# -*- coding:utf-8 -*- from __future__ import absolute_import from __future__", "= 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST", "= 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5", "#DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio =", "1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh =", "= 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3", "#EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1", "cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh = 0.8", "# cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh", "0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt =", "= False # #EAST parmas # cfg.det_east_score_thresh = 0.8 #", "-*- from __future__ import absolute_import from __future__ import division from", "\"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh", "# #EAST parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh =", "from __future__ import division from __future__ import print_function class Config(object):", "'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio", "for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len", "960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh", "cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False #", "0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving", "# cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt = False", "Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir =", "coding:utf-8 -*- from __future__ import absolute_import from __future__ import division", "__future__ import print_function class Config(object): pass def read_params(): cfg =", "= Config() #params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir", "absolute_import from __future__ import division from __future__ import print_function class", "cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type", "parmas # cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 #", "= 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False cfg.use_tensorrt", "Config(object): pass def read_params(): cfg = Config() #params for text", "text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len =", "# cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving =", "cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB", "cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST parmas #", "print_function class Config(object): pass def read_params(): cfg = Config() #params", "\"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max'", "= 1.6 cfg.use_dilation = False # #EAST parmas # cfg.det_east_score_thresh", "#params for text detector cfg.det_algorithm = \"DB\" cfg.det_model_dir = \"./inference/ch_ppocr_mobile_v2.0_det_infer/\"", "def read_params(): cfg = Config() #params for text detector cfg.det_algorithm", "parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6", "0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation = False # #EAST parmas", "import division from __future__ import print_function class Config(object): pass def", "division from __future__ import print_function class Config(object): pass def read_params():", "class Config(object): pass def read_params(): cfg = Config() #params for", "cfg.det_east_score_thresh = 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh =", "cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh =", "= 0.8 # cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2", "cfg.det_east_cover_thresh = 0.1 # cfg.det_east_nms_thresh = 0.2 cfg.use_pdserving = False", "-*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import", "import absolute_import from __future__ import division from __future__ import print_function", "__future__ import absolute_import from __future__ import division from __future__ import", "= \"./inference/ch_ppocr_mobile_v2.0_det_infer/\" cfg.det_limit_side_len = 960 cfg.det_limit_type = 'max' #DB parmas", "cfg.det_limit_type = 'max' #DB parmas cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh =", "read_params(): cfg = Config() #params for text detector cfg.det_algorithm =", "pass def read_params(): cfg = Config() #params for text detector", "= 0.2 cfg.use_pdserving = False cfg.use_tensorrt = False return cfg", "from __future__ import print_function class Config(object): pass def read_params(): cfg", "__future__ import division from __future__ import print_function class Config(object): pass", "cfg.det_db_thresh = 0.3 cfg.det_db_box_thresh = 0.5 cfg.det_db_unclip_ratio = 1.6 cfg.use_dilation" ]
[ "m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def", "torch.cat( [out,skip_x], 1 ) out = self.res(out) return out class", "32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) #", "torch.nn as nn import torch as torch import math import", "self.res2 = Block( planes,planes, 1) def forward(self, x): out =", "self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) #", ") # 1x1 conv for mathability if self.use_visi: self.visi_conv =", "nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes)", "= DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip", "deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def", "= nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3,", "s2, s3, s4 ) if self.use_visi: visiout = self.visibility( merged_encode,", "self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64", "self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual)", "t2, t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1", "<filename>networks/larflow/models/larflow_uresnet.py import torch.nn as nn import torch as torch import", "\" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print", "= self.bn1(out) out = self.relu1(out) out = self.conv2(out) out =", "= self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 =", "decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if", ") if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict =", "32->16 # 1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features,", "self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1 conv", "= stride # if stride >1, then we need to", "= self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes:", "self._showsizes = showsizes # print size at each layer self.use_visi", "self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 =", "connections out = torch.cat( [out,skip_x], 1 ) out = self.res(out)", "class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1):", "# 32->16 # 1x1 conv for flow self.flow_conv = nn.Conv2d(", "\" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target):", "expansion = 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__()", "1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv for", "): super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1", "\",x1.size() print \" x2: \",x2.size() print \" x3: \",x3.size() print", "/ n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes,", "self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 =", "self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual)", "# ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\"", "nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res =", "inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1", "nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1", "def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes,", "matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16", "bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 =", "self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64", "self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features", "_make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes,", "x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x", "each layer self.use_visi = use_visi # Encoder # stem #", "torch as torch import math import torch.utils.model_zoo as model_zoo ###########################################################", "as model_zoo ########################################################### # # U-ResNet # U-net witih ResNet", "self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128", "self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3,", "# U-net from (cite) # # meant to be copy", "__init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual path", "x0 = self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2", "self.inplanes ) # 32->16 # 1x1 conv for flow self.flow_conv", "stride=2) # 256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features", "= self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual =", "self.bn1(out) out = self.relu1(out) out = self.conv2(out) out = self.bn2(out)", "def forward(self, x): out = self.res1(x) out = self.res2(out) return", "forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out =", "self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv", "stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes)", "self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1 conv for", "= nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res", "t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 )", "out = self.bn2(out) if self.bypass is not None: outbp =", "class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 =", "ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem", "None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1,", "out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__()", "self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer(", "import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet # U-net", "self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 # 1x1", "= nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride", ") # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2", "if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda", "= self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding:", "conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1,", "target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1,", "= self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer(", "decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes:", "if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def", "= self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4", "self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if", "super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def", "flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv(", "= self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x", "self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16", "bias=True ) # 1x1 conv for mathability if self.use_visi: self.visi_conv", "self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8,", "to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print", "# 2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) #", "target_encode, t0, t1, t2, t3, t4 = self.encode(target) merged_encode =", "self.bypass is not None: outbp = self.bypass(x) out += outbp", "+= outbp else: out += x out = self.relu(out) return", "def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes,", "to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print", "class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__()", "inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes,", "as nn import torch as torch import math import torch.utils.model_zoo", "self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print", "super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size at each", "dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \"", ") flowout = self.flow( merged_encode, s0, s1, s2, s3, s4", "= self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out =", "self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if", "= self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x", "print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes:", "print \" x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4", "out = self.relu1(out) out = self.conv2(out) out = self.bn2(out) if", "self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256", "= nn.ReLU(inplace=True) self.stride = stride # if stride >1, then", "self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes):", "x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \"", "\",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 = self.encode(src)", "if self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2, t3,", "16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3", "2, kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes, 0=not", "# 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features )", "super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1,", "self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4):", "= self.bn2(out) if self.bypass is not None: outbp = self.bypass(x)", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1:", "self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True )", "########################################################### # # U-ResNet # U-net witih ResNet modules #", "self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu =", "flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after", "stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out", "self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8,", "s0, s1, s2, s3, s4 ) if self.use_visi: visiout =", "nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out = self.bn1(out)", "self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2)", "bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x)", "Block( planes,planes, 1) def forward(self, x): out = self.res1(x) out", "self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2,", "size at each layer self.use_visi = use_visi # Encoder #", "mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1,", "= self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout =", "for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0,", ") self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2", "forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode,", "stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes,", "super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False", "super(Preactivation, self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 =", "self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16,", "= self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4", "self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1", "self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8,", "self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print \" softmax:", "if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride,", "of caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3", "prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\"", "nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1,", "inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes,", "x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after", "return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion =", "= self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout", "= self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1", "512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) #", "stride >1, then we need to subsamble the input if", "MicroBooNE # to label track/shower pixels # # resnet implementation", "math import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet #", "= nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,", "self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4,", "stride self.bypass = None if inplanes!=planes or stride>1: self.bypass =", "self.enc_layer4(x3) x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding: \"", "nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False)", "self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x =", "dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \"", "self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2,", "self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16,", "self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes,", "self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv =", "else: bypass = self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual)", "1 ) out = self.res(out) return out class LArFlowUResNet(nn.Module): def", "self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4,", "initialization for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d):", "else: self.shortcut = None def forward(self, x): if self.shortcut is", "nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride)", "nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels", "= self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x =", "self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4,", "self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer(", "self.relu = nn.ReLU(inplace=True) self.stride = stride # if stride >1,", "self.flow_conv( flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout )", "nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) #", "x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda", "if stride >1, then we need to subsamble the input", "= self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 =", "= stride self.bypass = None if inplanes!=planes or stride>1: self.bypass", "self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self,", "Encoder # stem # one big stem self.conv1 = nn.Conv2d(input_channels,", "nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3", "32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4", "return x def forward(self, src, target): if self._showsizes: print \"input:", "self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow(", "print size at each layer self.use_visi = use_visi # Encoder", "merged_encode, s0, s1, s2, s3, s4 ) if self.use_visi: visiout", "self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16,", "\"after encoding: \" print \" x1: \",x1.size() print \" x2:", "self.stride = stride # if stride >1, then we need", "self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu", "residual = self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual", "= self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict =", "# 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128", "self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self,", "in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0]", "= nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if inplanes!=planes", "# resnet implementation from pytorch.torchvision module # U-net from (cite)", "self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x)", "kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 =", "\",x3.size() print \" x4: \",x4.size() print \" x5: \",x5.size() return", "32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2,", "x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda", "\",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target): if self._showsizes:", "self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial", "self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3,", "256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes", "self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2)", "= self.encode(src) target_encode, t0, t1, t2, t3, t4 = self.encode(target)", "[target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0, s1, s2,", "\"\"\" decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4) if", "big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True)", "# 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 )", "self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer(", "= self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 #", ") # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4", "kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes, 0=not vis,", ") self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) #", "out = self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes,", "self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer(", "bypass = x else: bypass = self.shortcut(x) residual = self.conv1(x)", "stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes,", "self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x):", "planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2", "class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes,", "# residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1", "self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes,", "None: outbp = self.bypass(x) out += outbp else: out +=", "padding=0, bias=True ) # 2 classes, 0=not vis, 1=vis self.visi_softmax", "= nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv", "self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4,", "# meant to be copy of caffe version # ###########################################################", "if self.shortcut is None: bypass = x else: bypass =", "use_visi # Encoder # stem # one big stem self.conv1", "from (cite) # # meant to be copy of caffe", "encode(self,x): # stem x = self.conv1(x) x = self.bn1(x) x0", "residual = self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual", "bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size())", "x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5", "residual = self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out", "self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False )", "# # Semantic segmentation network used by MicroBooNE # to", "self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4,", "\",x2.size() print \" x3: \",x3.size() print \" x4: \",x4.size() print", "stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 =", "residual = self.bn3(residual) out = bypass+residual out = self.relu(out) return", "dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \"", "self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual)", "self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes,", "= self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x", "kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x):", "def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() # residual", "x3: \",x3.size() print \" x4: \",x4.size() print \" x5: \",x5.size()", "# Encoder # stem # one big stem self.conv1 =", "self.use_visi = use_visi # Encoder # stem # one big", "kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self,", "resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def", "self.inplanes, self.inplanes ) # 32->16 # 1x1 conv for flow", "self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True", "inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride)", "= 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1", "U-net witih ResNet modules # # Semantic segmentation network used", "\" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print", "256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) #", "= Block( planes,planes, 1) def forward(self, x): out = self.res1(x)", "512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) #", "self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2,", "resnetplanes ) def encode(self,x): # stem x = self.conv1(x) x", "stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) #", "= self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3", "return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ):", "showsizes # print size at each layer self.use_visi = use_visi", "= self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1 =", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3:", "= None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes,", "out = self.conv2(out) out = self.bn2(out) if self.bypass is not", "planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1", "= self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual) residual =", "Semantic segmentation network used by MicroBooNE # to label track/shower", "= self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 =", "\" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print", "3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1)", "128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) #", "iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\"", "self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual = self.conv3(residual)", "\" x1: \",x1.size() print \" x2: \",x2.size() print \" x3:", "= nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2", "self.relu1(out) out = self.conv2(out) out = self.bn2(out) if self.bypass is", "self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8,", "is not None: outbp = self.bypass(x) out += outbp else:", "= nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 =", "self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1", "self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\"", ") def encode(self,x): # stem x = self.conv1(x) x =", "self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x =", "U-ResNet # U-net witih ResNet modules # # Semantic segmentation", "if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2)", "vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in", "self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4,", "): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x):", "if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1]", "self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features = self.inplanes", "s4 ) if self.use_visi: visiout = self.visibility( merged_encode, t0, t1,", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2:", "self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 =", "out = self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module):", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3:", "# concat skip connections out = torch.cat( [out,skip_x], 1 )", "x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4", "self.bypass(x) out += outbp else: out += x out =", "# 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 )", "= self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out =", "# 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer(", "1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1,", "self.visibility( merged_encode, t0, t1, t2, t3, t4 ) flow_predict =", "s3, s4 ) if self.use_visi: visiout = self.visibility( merged_encode, t0,", "deconvplanes, resnetplanes ) def encode(self,x): # stem x = self.conv1(x)", "stride=1, padding=0, bias=True ) # 2 classes, 0=not vis, 1=vis", "= m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n))", "iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\"", ">1, then we need to subsamble the input if stride>1:", "nn.ReLU(inplace=True) self.stride = stride # if stride >1, then we", "DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer(", "= nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)", "path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes,", "kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x):", "self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x =", "inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes", "self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2, t3, t4", "self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability", "n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes,", "else: out += x out = self.relu(out) return out class", "x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \"", "1 ) flowout = self.flow( merged_encode, s0, s1, s2, s3,", "out = bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module):", "iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\"", "self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else:", "self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if", "be copy of caffe version # ########################################################### def conv3x3(in_planes, out_planes,", "self.relu = nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out", "resnet implementation from pytorch.torchvision module # U-net from (cite) #", "= conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True)", "self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) #", "x5 = self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print", "self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if", "conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2", "forward(self, x): out = self.conv1(x) out = self.bn1(out) out =", "out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation,", "* m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m,", "self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x =", "if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0)", "x): out = self.conv1(x) out = self.bn1(out) out = self.relu1(out)", "x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4) if", "x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow", "x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda", "bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 =", "\" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print", "prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\"", "__init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1,", "= self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5:", "super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes)", "nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes)", "label track/shower pixels # # resnet implementation from pytorch.torchvision module", "kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,", "pixels # # resnet implementation from pytorch.torchvision module # U-net", "ResNet modules # # Semantic segmentation network used by MicroBooNE", "to subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else:", "planes,planes, 1) def forward(self, x): out = self.res1(x) out =", "= self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x", "self.shortcut = None def forward(self, x): if self.shortcut is None:", "if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 )", "stem x = self.conv1(x) x = self.bn1(x) x0 = self.relu1(x)", "nn import torch as torch import math import torch.utils.model_zoo as", "self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat", "self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x =", "kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1 =", "nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True)", "= torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0,", "stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1,", "stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) #", "print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x =", "+= x out = self.relu(out) return out class Bottleneck(nn.Module): def", "x def forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\"", "self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x", "# to label track/shower pixels # # resnet implementation from", "out += outbp else: out += x out = self.relu(out)", "to be copy of caffe version # ########################################################### def conv3x3(in_planes,", "print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\"", "version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with", "m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self,", "self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 =", "= self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer(", ") # 32->16 # 1x1 conv for flow self.flow_conv =", "_make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes,", "nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2,", "nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,", "return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ):", "print \" x1: \",x1.size() print \" x2: \",x2.size() print \"", "self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes)", "self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if", "pytorch.torchvision module # U-net from (cite) # # meant to", "= nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if isinstance(m,", "self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if", "elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2):", "with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module):", "= nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1", "src_encode, s0, s1, s2, s3, s4 = self.encode(src) target_encode, t0,", "self.encode(src) target_encode, t0, t1, t2, t3, t4 = self.encode(target) merged_encode", "outbp else: out += x out = self.relu(out) return out", "# if stride >1, then we need to subsamble the", "is None: bypass = x else: bypass = self.shortcut(x) residual", "self.shortcut is None: bypass = x else: bypass = self.shortcut(x)", "#self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1", "padding=0, bias=True ) # 1x1 conv for mathability if self.use_visi:", "########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return", "dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \"", "visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict", "if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0)", "# U-ResNet # U-net witih ResNet modules # # Semantic", "= showsizes # print size at each layer self.use_visi =", "self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if", "= self.res2(out) return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv", "64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) #", "deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes )", "stride=stride, padding=1, bias=False) # if stride >1, then we need", "= self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print \"", "x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda", "s4 = self.encode(src) target_encode, t0, t1, t2, t3, t4 =", "\" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print", "dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \"", "self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes", "None: bypass = x else: bypass = self.shortcut(x) residual =", "path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes)", "= self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3", "= nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) #", "x2: \",x2.size() print \" x3: \",x3.size() print \" x4: \",x4.size()", "at each layer self.use_visi = use_visi # Encoder # stem", "segmentation network used by MicroBooNE # to label track/shower pixels", "else: visi_predict = None if self._showsizes: print \" softmax: \",x.size()", "planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 =", "= self.res1(x) out = self.res2(out) return out class ConvTransposeLayer(nn.Module): def", "def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes,", "layer self.use_visi = use_visi # Encoder # stem # one", "x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4):", "= self.bn3(residual) out = bypass+residual out = self.relu(out) return out", "128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 #", "x = self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda", "padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out =", "self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer(", "nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride # if stride", "self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128", "self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2,", "model_zoo ########################################################### # # U-ResNet # U-net witih ResNet modules", "merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode,", "print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes:", "t0, t1, t2, t3, t4 = self.encode(target) merged_encode = torch.cat(", "= self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5:", "\" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print", "# 1x1 conv for flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1,", "= torch.cat( [out,skip_x], 1 ) out = self.res(out) return out", "= nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) #", "= self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes,", "DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block(", "self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer(", "0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m", "import math import torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet", "out = self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self, inplanes,", "self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 =", "self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32", "t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode], 1 ) flowout", "m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d):", "= conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass", "DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1) def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections", ") if self.use_visi: visiout = self.visibility( merged_encode, t0, t1, t2,", "print \" x3: \",x3.size() print \" x4: \",x4.size() print \"", "bias=True ) # 2 classes, 0=not vis, 1=vis self.visi_softmax =", "initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1", "def forward(self,x,skip_x): out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out", "= self.bypass(x) out += outbp else: out += x out", "kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1, then we", "= self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual =", "if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1)", "print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes:", "visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.visi_dec_layer5(merged_encode,x4)", "nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride =", "skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem x =", "self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 =", "self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if", "def forward(self, src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda", "bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes,", "= nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)", "print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes:", "self).__init__() self._showsizes = showsizes # print size at each layer", "x = self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x", "self.relu2 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1,", "iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction", "import torch as torch import math import torch.utils.model_zoo as model_zoo", "self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x", "if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2)", "= nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 =", "self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4,", "if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict)", "out = torch.cat( [out,skip_x], 1 ) out = self.res(out) return", "nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x): if self.shortcut", "= Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self, x):", "s1, s2, s3, s4 ) if self.use_visi: visiout = self.visibility(", "out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3,", "stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu", "self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes,", "self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size", "merged_encode, t0, t1, t2, t3, t4 ) flow_predict = self.flow_conv(", "def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual", "self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes,", "stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) #", "self.conv3(residual) residual = self.bn3(residual) out = bypass+residual out = self.relu(out)", "bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,", "__init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual path", "def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet,", "[out,skip_x], 1 ) out = self.res(out) return out class LArFlowUResNet(nn.Module):", "x1: \",x1.size() print \" x2: \",x2.size() print \" x3: \",x3.size()", "= self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x", "math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self,", "self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32", ") # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8", "x = self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0) x1", "residual = self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual", "class PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__()", "residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True) self.conv1 =", "self.bn1(residual) residual = self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual)", "planes, stride=1 ): super(Preactivation, self).__init__() # residual path self.bn1 =", "None: bypass = x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module):", "# print size at each layer self.use_visi = use_visi #", ") # 2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1)", "def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes,", "modules # # Semantic segmentation network used by MicroBooNE #", "\"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3)", "self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)", "self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1", "self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64 self.enc_layer3 =", "self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability if", "inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0,", "print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4", "# initialization for m in self.modules(): if isinstance(m, nn.Conv2d) or", "= self.conv2(out) out = self.bn2(out) if self.bypass is not None:", ") flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict =", "x out = self.relu(out) return out class Bottleneck(nn.Module): def __init__(self,", "iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\"", "None def forward(self, x): if self.shortcut is None: bypass =", "128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) #", "# 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) # 32->64", "by MicroBooNE # to label track/shower pixels # # resnet", "t0, t1, t2, t3, t4 ) flow_predict = self.flow_conv( flowout", "kernel_size=1, stride=1, padding=0, bias=True ) # 1x1 conv for mathability", "self.conv2(out) out = self.bn2(out) if self.bypass is not None: outbp", "nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1", "out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes,", "=inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print size at", "stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) #", "= self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow", "self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes,", "iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\"", "self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride", "1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 =", "64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5", "forward(self, x): if self.shortcut is None: bypass = x else:", "skip connections out = torch.cat( [out,skip_x], 1 ) out =", "self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16,", "self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) # 2 classes,", "self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3) x5 = self.enc_layer5(x4)", "iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\"", "self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride #", "# initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True)", "meant to be copy of caffe version # ########################################################### def", "self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding flow #self.num_final_flow_features =", "\"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False)", "\"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 =", "planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride >1, then", "dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \"", "module # U-net from (cite) # # meant to be", "planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 =", "\" x2: \",x2.size() print \" x3: \",x3.size() print \" x4:", "(cite) # # meant to be copy of caffe version", "s1, s2, s3, s4 = self.encode(src) target_encode, t0, t1, t2,", "= self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual =", "= self.flow( merged_encode, s0, s1, s2, s3, s4 ) if", "encoding: \" print \" x1: \",x1.size() print \" x2: \",x2.size()", "bias=False) # if stride >1, then we need to subsamble", ") # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features", "return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): #", "# # meant to be copy of caffe version #", "flow self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True", "planes, stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1 =", "= x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1):", "self.bypass = None if inplanes!=planes or stride>1: self.bypass = nn.Conv2d(inplanes,", "\" x4: \",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def", "self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer(", "track/shower pixels # # resnet implementation from pytorch.torchvision module #", "\" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes: print", "x = self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda", "planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes,", "self.flow( merged_encode, s0, s1, s2, s3, s4 ) if self.use_visi:", "nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes,", "nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 =", "= nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2,", "stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ):", "self.stride = stride self.bypass = None if inplanes!=planes or stride>1:", "m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif", "\"\"\" x = self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print", "self.inplanes*8, self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32,", ") # 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes", "one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3,", "x): if self.shortcut is None: bypass = x else: bypass", "x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda", "self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] *", "caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution", "self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8,", ") # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4", "t3, t4 ) flow_predict = self.flow_conv( flowout ) if self.use_visi:", "if self.bypass is not None: outbp = self.bypass(x) out +=", ") visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes:", "decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if", "bypass = self.shortcut(x) residual = self.conv1(x) residual = self.bn1(residual) residual", "visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print", "= self.visi_softmax(visi_predict) else: visi_predict = None if self._showsizes: print \"", "nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer", "def encode(self,x): # stem x = self.conv1(x) x = self.bn1(x)", "src, target): if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0,", "forward(self, x): out = self.res1(x) out = self.res2(out) return out", "the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut =", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer2(x,x1) if self._showsizes: print \" dec2:", "subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut", "= self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16 #", "or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0,", "#self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2,", "out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def", "outbp = self.bypass(x) out += outbp else: out += x", "\" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print", "bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride", "\" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to", "we need to subsamble the input if stride>1: self.shortcut =", "= self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual =", "class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes", "# 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8, self.inplanes*16, stride=2) # 128->256", "# 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512", "import torch.nn as nn import torch as torch import math", "residual = self.conv1(x) residual = self.bn1(residual) residual = self.relu(residual) residual", "self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.relu2", "layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d(", "dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \"", "self.inplanes*16, stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2)", "self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2 =", "for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1,", "torch import math import torch.utils.model_zoo as model_zoo ########################################################### # #", "padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1", "padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32", "self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4,", "self).__init__() # residual path self.bn1 = nn.BatchNorm2d(inplanes) self.relu1 = nn.ReLU(inplace=True)", "1) def forward(self, x): out = self.res1(x) out = self.res2(out)", "isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] *", "out = self.bn1(out) out = self.relu1(out) out = self.conv2(out) out", "self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16,", "\" x3: \",x3.size() print \" x4: \",x4.size() print \" x5:", "not None: outbp = self.bypass(x) out += outbp else: out", "nn.BatchNorm2d(planes) self.stride = stride self.bypass = None if inplanes!=planes or", "padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out =", "bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False)", "ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4,", "print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes:", "\",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4:", "= self.flow_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return", "return out class ConvTransposeLayer(nn.Module): def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d(", "self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.visi_dec_layer3 = self._make_decoding_layer(", "1x1 conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes,", "self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3", "dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src, target): if", "self.flow_dec_layer4(x,x3) if self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x =", "bypass = x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def", "visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None if", "torch.utils.model_zoo as model_zoo ########################################################### # # U-ResNet # U-net witih", "m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n =", "self._showsizes: print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if", "planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride", "self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes,", "self.inplanes*4, stride=2) # 32->64 self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2)", "nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True)", "= bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module): def", "# 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 )", "Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() #", "bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes,", "def __init__(self,deconv_inplanes,skip_inplanes,deconv_outplanes,res_outplanes): super(ConvTransposeLayer,self).__init__() self.deconv = nn.ConvTranspose2d( deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2,", "residual = self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual", "= self._make_encoding_layer( self.inplanes*1, self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer(", "self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer(", "decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes:", "= None if self._showsizes: print \" softmax: \",x.size() return flow_predict,visi_predict", "t4 ) flow_predict = self.flow_conv( flowout ) if self.use_visi: visi_predict", "s2, s3, s4 = self.encode(src) target_encode, t0, t1, t2, t3,", "= self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 )", "residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 =", "stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes,", "self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200 # decoding", "Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1) def forward(self, x): out", "\"\"\" decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if", "self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16,", "= nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 =", "= None def forward(self, x): if self.shortcut is None: bypass", "U-net from (cite) # # meant to be copy of", "self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2,", "self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.flow_dec_layer4 =", "self.conv1(x) x = self.bn1(x) x0 = self.relu1(x) x = self.pool1(x0)", "witih ResNet modules # # Semantic segmentation network used by", "t1, t2, t3, t4 ) flow_predict = self.flow_conv( flowout )", "print \" dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes:", "to label track/shower pixels # # resnet implementation from pytorch.torchvision", "self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu1 =", "else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1", "self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1,", "= nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride = stride # if", "t2, t3, t4 ) flow_predict = self.flow_conv( flowout ) if", "is_cuda=\",x.is_cuda src_encode, s0, s1, s2, s3, s4 = self.encode(src) target_encode,", "dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to", "decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16,", "self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2", "= self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride)", "self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1 =", "padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class BasicBlock(nn.Module): expansion", "# 64->32 self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes )", "t1, t2, t3, t4 = self.encode(target) merged_encode = torch.cat( [target_encode,src_encode],", "classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for", "self.visi_conv( visiout ) visi_predict = self.visi_softmax(visi_predict) else: visi_predict = None", "self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.num_final_flow_features ) # 32->200", "def forward(self, x): if self.shortcut is None: bypass = x", "used by MicroBooNE # to label track/shower pixels # #", "= self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2 =", "showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes #", "self.inplanes*4 ) # 128->64 self.flow_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2,", "nn.LogSoftmax(dim=1) # initialization for m in self.modules(): if isinstance(m, nn.Conv2d)", "\"after decoding:\" print \" dec5: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer4(x,x3)", "= self.flow_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x", "padding=1, bias=False) # if stride >1, then we need to", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1:", "planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes", "self._showsizes: print \"after encoding: \" print \" x1: \",x1.size() print", "if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def", "conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass =", "if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1)", "self.bn1 = nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes)", "self.num_final_flow_features ) # 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5", "self.visi_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes, self.inplanes ) # 32->16", "iscuda=\",x.is_cuda x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\"", "as torch import math import torch.utils.model_zoo as model_zoo ########################################################### #", "or stride>1: self.bypass = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False)", "= self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return", "# decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5", "stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self, x): out", "# residual path self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1", "m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()", "def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x =", "self.relu(residual) residual = self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual)", "= self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat( [out,skip_x],", "self.inplanes*2, stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2)", "flowout = self.flow( merged_encode, s0, s1, s2, s3, s4 )", "input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None", "nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True ) # 1x1", "conv layer self.bn1 = nn.BatchNorm2d(self.inplanes) self.relu1 = nn.ReLU(inplace=True) self.pool1 =", "x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x", "# 256->128 self.visi_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 )", "= nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) # if stride", ") # 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes )", "# 256->512 # decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features =", "# decoding matchability if self.use_visi: self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16,", "# stem x = self.conv1(x) x = self.bn1(x) x0 =", "residual = self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out", "conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2,", "x = self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1) x3", "= self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16,", "copy of caffe version # ########################################################### def conv3x3(in_planes, out_planes, stride=1):", "# U-net witih ResNet modules # # Semantic segmentation network", "out class Bottleneck(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Bottleneck,", "self.visi_dec_layer5 = self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256", "# 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 )", "self.visi_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print \" dec5: \",x.size(),\"", "stride=1, padding=3, bias=True) # initial conv layer self.bn1 = nn.BatchNorm2d(self.inplanes)", "= nn.ReLU(inplace=True) def forward(self, x): out = self.conv1(x) out =", "# # resnet implementation from pytorch.torchvision module # U-net from", "self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) # 256->512 # decoding", "= nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self, x): if", "flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 = self._make_decoding_layer(", "n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. /", "\" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding", "inplanes, planes, stride=1 ): super(Bottleneck, self).__init__() # residual path self.conv1", "= nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False) self.bn2 =", "padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes, kernel_size=1,", "s3, s4 = self.encode(src) target_encode, t0, t1, t2, t3, t4", "deconv_inplanes, deconv_outplanes, kernel_size=4, stride=2, padding=1, bias=False ) self.res = DoubleResNet(BasicBlock,deconv_outplanes+skip_inplanes,res_outplanes,stride=1)", "torch.cat( [target_encode,src_encode], 1 ) flowout = self.flow( merged_encode, s0, s1,", "flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after", "self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer(", "iscuda=\",x.is_cuda x = self.visi_dec_layer2(x,x1) if self._showsizes: print \" dec2: \",x.size(),\"", "use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes = showsizes # print", "\",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction", "= self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3,", "planes) self.bn2 = nn.BatchNorm2d(planes) self.stride = stride self.bypass = None", "stem # one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7,", "self.bn3(residual) out = bypass+residual out = self.relu(out) return out class", "if self._showsizes: print \"after encoding: \" print \" x1: \",x1.size()", "stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False) else: self.shortcut = None def forward(self,", "LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes", "self.relu1 = nn.ReLU(inplace=True) self.pool1 = nn.MaxPool2d( 3, stride=2, padding=1 )", "__init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2 = Block( planes,planes, 1)", "concat skip connections out = torch.cat( [out,skip_x], 1 ) out", "= self.relu1(out) out = self.conv2(out) out = self.bn2(out) if self.bypass", "\",x.size(),\" iscuda=\",x.is_cuda return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow", "def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x =", "convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class", "self.relu1(x) x = self.pool1(x0) x1 = self.enc_layer1(x) x2 = self.enc_layer2(x1)", "nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2", "input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes =", "print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer1(x,x0) if self._showsizes:", "self.flow_conv = nn.Conv2d( self.num_final_flow_features, 1, kernel_size=1, stride=1, padding=0, bias=True )", "if self._showsizes: print \"input: \",x.size(),\" is_cuda=\",x.is_cuda src_encode, s0, s1, s2,", "self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat( [out,skip_x], 1", "self.enc_layer3 = self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 =", "return x def visibility(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\"", "isinstance(m,nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2.", "self.bn2(out) if self.bypass is not None: outbp = self.bypass(x) out", "out += x out = self.relu(out) return out class Bottleneck(nn.Module):", "print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x def forward(self, src,", "self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2", "return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False,", "inplanes, skipplanes, deconvplanes, resnetplanes ) def encode(self,x): # stem x", "num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__() self._showsizes", "\",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer4(x,x3) if self._showsizes: print \" dec4:", "print \" dec2: \",x.size(),\" iscuda=\",x.is_cuda x = self.visi_dec_layer1(x,x0) if self._showsizes:", "self.inplanes, kernel_size=7, stride=1, padding=3, bias=True) # initial conv layer self.bn1", ") # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2", "def forward(self, x): out = self.conv1(x) out = self.bn1(out) out", "* m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1)", "m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def", "# stem # one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes,", "network used by MicroBooNE # to label track/shower pixels #", "self.inplanes*2, self.inplanes, self.inplanes ) # 32->16 self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2,", "= use_visi # Encoder # stem # one big stem", "x else: bypass = self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__()", "64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) # 32->16", "self.inplanes, self.num_final_flow_features ) # 32->200 # decoding matchability if self.use_visi:", "self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 = self.enc_layer4(x3)", "visi_predict = None if self._showsizes: print \" softmax: \",x.size() return", "self.shortcut(x) class DoubleResNet(nn.Module): def __init__(self,Block,inplanes,planes,stride=1): super(DoubleResNet,self).__init__() self.res1 = Block(inplanes,planes,stride) self.res2", ") # 32->200 # decoding matchability if self.use_visi: self.visi_dec_layer5 =", "PreactivationBlock(nn.Module): def __init__(self, inplanes, planes, stride=1 ): super(Preactivation, self).__init__() #", "for m in self.modules(): if isinstance(m, nn.Conv2d) or isinstance(m,nn.ConvTranspose2d): n", "self.enc_layer5(x4) if self._showsizes: print \"after encoding: \" print \" x1:", "print \"after encoding: \" print \" x1: \",x1.size() print \"", "__init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes,", "decoding flow #self.num_final_flow_features = self.inplanes self.num_final_flow_features = self.inplanes self.flow_dec_layer5 =", "self._make_decoding_layer( self.inplanes*32*2, self.inplanes*16, self.inplanes*16, self.inplanes*16 ) # 512->256 self.visi_dec_layer4 =", "stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes,", "out = self.deconv(x,output_size=skip_x.size()) # concat skip connections out = torch.cat(", "nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def", "then we need to subsamble the input if stride>1: self.shortcut", "= self.conv1(x) out = self.bn1(out) out = self.relu1(out) out =", "nn.BatchNorm2d(planes) self.relu1 = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 =", "= nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes)", "# 1x1 conv for mathability if self.use_visi: self.visi_conv = nn.Conv2d(", "nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0, bias=True ) # 2", "1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization for m in self.modules():", "\"\"\" x = self.flow_dec_layer5(merged_encode,x4) if self._showsizes: print \"after decoding:\" print", "= nn.MaxPool2d( 3, stride=2, padding=1 ) self.enc_layer1 = self._make_encoding_layer( self.inplanes*1,", "= self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.flow_dec_layer2", "): super(Bottleneck, self).__init__() # residual path self.conv1 = nn.Conv2d(inplanes, planes,", "stride # if stride >1, then we need to subsamble", "self.inplanes*4 ) # 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2,", "def __init__(self, inplanes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes,", ") # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8", "\",x4.size() print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\"", "self.conv1(x) out = self.bn1(out) out = self.relu1(out) out = self.conv2(out)", "out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True):", "self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8, self.inplanes*8 ) # 256->128 self.flow_dec_layer3 =", "isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_encoding_layer(self, inplanes, planes, stride=2): return", "= nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True)", "= self.conv2(residual) residual = self.bn2(residual) residual = self.relu(residual) residual =", ") out = self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self,", "# 128->64 self.visi_dec_layer2 = self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 )", "stride=1, padding=0, bias=True ) # 1x1 conv for mathability if", "visiout = self.visibility( merged_encode, t0, t1, t2, t3, t4 )", "conv3x3(in_planes, out_planes, stride=1): \"\"\"3x3 convolution with padding\"\"\" return nn.Conv2d(in_planes, out_planes,", "from pytorch.torchvision module # U-net from (cite) # # meant", "kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes,", "s0, s1, s2, s3, s4 = self.encode(src) target_encode, t0, t1,", "skipplanes, deconvplanes, resnetplanes ): return ConvTransposeLayer( inplanes, skipplanes, deconvplanes, resnetplanes", "is None: bypass = x else: bypass = self.shortcut(x) class", "need to subsamble the input if stride>1: self.shortcut = nn.Conv2d(inplanes,planes,kernel_size=1,stride=stride,bias=False)", "= self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) # 128->64 self.visi_dec_layer2", "__init__(self, num_classes=3, input_channels=3, inplanes=16, showsizes=False, use_visi=True): self.inplanes =inplanes super(LArFlowUResNet, self).__init__()", "self.relu(residual) residual = self.conv3(residual) residual = self.bn3(residual) out = bypass+residual", "= nn.Conv2d(planes, planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu =", "flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\" x = self.flow_dec_layer5(merged_encode,x4)", "= self.visibility( merged_encode, t0, t1, t2, t3, t4 ) flow_predict", "= self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer(", "x = self.visi_dec_layer3(x,x2) if self._showsizes: print \" dec3: \",x.size(),\" iscuda=\",x.is_cuda", "BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1): super(BasicBlock,", "# Semantic segmentation network used by MicroBooNE # to label", "x): out = self.res1(x) out = self.res2(out) return out class", "self.visi_dec_layer1(x,x0) if self._showsizes: print \" dec1: \",x.size(),\" iscuda=\",x.is_cuda return x", "# 64->32 #self.flow_dec_layer1 = self._make_decoding_layer( self.inplanes*2, self.inplanes, self.inplanes ) #", "bypass+residual out = self.relu(out) return out class PreactivationBlock(nn.Module): def __init__(self,", "# one big stem self.conv1 = nn.Conv2d(input_channels, self.inplanes, kernel_size=7, stride=1,", "return DoubleResNet(BasicBlock,inplanes,planes,stride=stride) def _make_decoding_layer(self, inplanes, skipplanes, deconvplanes, resnetplanes ): return", "kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.stride =", "self.inplanes*16 ) # 512->256 self.visi_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8,", "2 classes, 0=not vis, 1=vis self.visi_softmax = nn.LogSoftmax(dim=1) # initialization", "= self.enc_layer1(x) x2 = self.enc_layer2(x1) x3 = self.enc_layer3(x2) x4 =", "# # U-ResNet # U-net witih ResNet modules # #", "iscuda=\",x.is_cuda return x def forward(self, src, target): if self._showsizes: print", "print \" x5: \",x5.size() return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding", "flowout ) if self.use_visi: visi_predict = self.visi_conv( visiout ) visi_predict", "256->128 self.flow_dec_layer3 = self._make_decoding_layer( self.inplanes*8, self.inplanes*4, self.inplanes*4, self.inplanes*4 ) #", "\" print \" x1: \",x1.size() print \" x2: \",x2.size() print", "= self.relu(out) return out class Bottleneck(nn.Module): def __init__(self, inplanes, planes,", "x else: bypass = self.shortcut(x) residual = self.conv1(x) residual =", "= self._make_decoding_layer( self.inplanes*4, self.inplanes*2, self.inplanes*2, self.inplanes*2 ) # 64->32 self.visi_dec_layer1", "= x else: bypass = self.shortcut(x) residual = self.conv1(x) residual", "self._make_encoding_layer( self.inplanes*4, self.inplanes*8, stride=2) # 64->128 self.enc_layer4 = self._make_encoding_layer( self.inplanes*8,", "out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) out", "out = self.res(out) return out class LArFlowUResNet(nn.Module): def __init__(self, num_classes=3,", "self.inplanes*16 ) # 512->256 self.flow_dec_layer4 = self._make_decoding_layer( self.inplanes*16, self.inplanes*8, self.inplanes*8,", "stride=2) # 128->256 self.enc_layer5 = self._make_encoding_layer( self.inplanes*16, self.inplanes*32, stride=2) #", "if self.use_visi: self.visi_conv = nn.Conv2d( self.inplanes, 2, kernel_size=1, stride=1, padding=0,", "return x5,x0,x1,x2,x3,x4 def flow(self,merged_encode,x0,x1,x2,x3,x4): \"\"\" decoding to flow prediction \"\"\"", "stride=1) # 16->32 self.enc_layer2 = self._make_encoding_layer( self.inplanes*2, self.inplanes*4, stride=2) #", "implementation from pytorch.torchvision module # U-net from (cite) # #", "dec4: \",x.size(),\" iscuda=\",x.is_cuda x = self.flow_dec_layer3(x,x2) if self._showsizes: print \"", "planes, kernel_size=1, stride=stride, padding=0, bias=False) self.relu = nn.ReLU(inplace=True) def forward(self,", "print \" x2: \",x2.size() print \" x3: \",x3.size() print \"" ]
[ "num_training_steps = args.max_steps if args.max_steps > 0 else len( train_data_loader)", "overlaps a bit the context of the previous feature. #", "range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's", "args import parse_args import paddlenlp as ppnlp from paddlenlp.data import", "start and end positions for i, tokenized_example in enumerate(tokenized_examples): #", "# The offset mappings will give us a map from", "2.0 (the \"License\"); # you may not use this file", "several features when a context is long, each of those", "in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank ==", "paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy(", "axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits,", "% (global_step, epoch + 1, step + 1, loss, args.logging_steps", "from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from", "+ \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def", "paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name", "# For validation, there is no need to compute start", "# Tokenize our examples with truncation and maybe padding, but", "in n for nd in [\"bias\", \"norm\"]) ] optimizer =", "if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name,", "print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:', time.time() -", "this span of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers']", "0 while sequence_ids[token_start_index] != 1: token_start_index += 1 # End", "compute start and end positions for i, tokenized_example in enumerate(tokenized_examples):", "answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index", "in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and len(all_start_logits):", "the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) #", "(to know what is the context and what is the", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "% args.logging_steps == 0: print( \"global step %d, epoch: %d,", "x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train", "import paddlenlp as ppnlp from paddlenlp.data import Pad, Stack, Tuple,", "long, each of those features having a # context that", "enumerate(tokenized_examples): # Grab the sequence corresponding to that example (to", "from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer", "not part of the context so it's easy to determine", "Rights Reserved. # Copyright 2018 The HuggingFace Inc. team. #", "%d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s\"", "if the answer is out of the span (in which", "time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps ==", "batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id),", "ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import", "a # context that overlaps a bit the context of", "and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:',", "checkpoint to:', output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples):", "is no need to compute start and end positions for", "and token_end_index to the two ends of the answer. #", "original context. This will # help us compute the start_positions", "train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features,", "# Can also write all_nbest_json and scores_diff_json files if needed", "return_list=True) num_training_steps = args.max_steps if args.max_steps > 0 else len(", "token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index +=", "there is no need to compute start and end positions", "the last word (edge case). while token_start_index < len(offsets) and", "token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1", "token_end_index to the two ends of the answer. # Note:", "\"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler,", "\"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) }", "use this file except in compliance with the License. #", "the same functionality as HuggingFace's prepare_train_features function. The main difference", "args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds =", "global_step = 0 tic_train = time.time() for epoch in range(num_train_epochs):", "2018 The HuggingFace Inc. team. # # Licensed under the", "input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step %", "shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\":", "example: %d\" % len(all_start_logits)) print('time per 1000:', time.time() - tic_eval)", "from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer),", "as basic data structure, while we use list of dictionary", "end_char = start_char + len(answers[0]) # Start token index of", "decay. # All bias and LayerNorm parameters are excluded. decay_params", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "= tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those", "start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] =", "dictionary instead. contexts = [examples[i]['context'] for i in range(len(examples))] questions", "License. # You may obtain a copy of the License", "also write all_nbest_json and scores_diff_json files if needed with open('prediction.json',", "False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and scores_diff_json", "= paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss =", "(o if sequence_ids[k] == 1 else None) for k, o", "feature is labeled with the CLS index). if not (offsets[token_start_index][0]", "break def prepare_validation_features(examples): # Tokenize our examples with truncation and", "global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to", "the question). sequence_ids = tokenized_example['token_type_ids'] # One example can give", "tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the token_start_index and", "text token_end_index -= 1 # Detect if the answer is", "parameters are excluded. decay_params = [ p.name for n, p", "under the License is distributed on an \"AS IS\" BASIS,", "optimizer.clear_grad() if global_step % args.save_steps == 0 or global_step ==", "a map from token to character position in the original", "end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss =", "PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The HuggingFace", "License for the specific language governing permissions and # limitations", "all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits,", "] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x:", "= tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end", "< len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index += 1", "1: token_end_index -= 1 # Minus one more to reach", "= paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy(", "span (in which case this feature is labeled with the", "else: # Otherwise move the token_start_index and token_end_index to the", "end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return", "rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" %", "in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples", "time import json import math from functools import partial import", "== num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples with", "Grab the sequence corresponding to that example (to know what", "+ len(answers[0]) # Start token index of the current span", "Detect if the answer is out of the span (in", "LayerNorm parameters are excluded. decay_params = [ p.name for n,", "= input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us a", "= criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps == 0:", "limitations under the License. import os import random import time", "\"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\":", "two ends of the answer. # Note: we could go", "as HuggingFace's prepare_train_features function. The main difference is # that", "logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions))", "else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples", "/ 2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() >", "answer. # Note: we could go after the last offset", "from args import parse_args import paddlenlp as ppnlp from paddlenlp.data", "i in range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))]", "start_logits, end_logits = y start_position, end_position = label start_position =", "our examples with truncation and maybe padding, but keep the", "per 1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx])", "the answer. # Note: we could go after the last", "functionality as HuggingFace's prepare_train_features function. The main difference is #", "batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda", "# need better way to get inner model of DataParallel", "tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else:", "what is the context and what is the question). sequence_ids", "= tokenized_example['offset_mapping'] # Grab the sequence corresponding to that example", "in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids,", "if len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing example:", "Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader =", "Set to None the offset_mapping that are not part of", "= model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if", "= y start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1)", "in compliance with the License. # You may obtain a", "weight decay. # All bias and LayerNorm parameters are excluded.", "offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else:", "== 0: print( \"global step %d, epoch: %d, batch: %d,", "BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import", "num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples with truncation", "Authors. All Rights Reserved. # Copyright 2018 The HuggingFace Inc.", "software # distributed under the License is distributed on an", "= paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss) /", "\"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad()", "x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0", "get inner model of DataParallel model_to_save = model._layers if isinstance(", "and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index", "criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps == 0: print(", "args.warmup_proportion) # Generate parameter names needed to perform weight decay.", "label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss +", "2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1:", "the current span in the text. token_start_index = 0 while", "# Detect if the answer is out of the span", "and offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] =", "step/s\" % (global_step, epoch + 1, step + 1, loss,", "know what is the context and what is the question).", "what is the question). sequence_ids = tokenized_example['token_type_ids'] # One example", "1: token_start_index += 1 # End token index of the", "= load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True)", "with the index of the CLS token. input_ids = tokenized_example[\"input_ids\"]", "with the CLS index). if not (offsets[token_start_index][0] <= start_char and", "paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from", "a stride. This results # in one example possible giving", "token_end_index -= 1 # Minus one more to reach actual", "This results # in one example possible giving several features", "if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model =", "License. import os import random import time import json import", "> 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type", "def prepare_validation_features(examples): # Tokenize our examples with truncation and maybe", "\"global step %d, epoch: %d, batch: %d, loss: %f, speed:", "= time.time() for batch in data_loader: input_ids, token_type_ids = batch", "LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset", "output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize", "token to character position in the original context. This will", "labeled with the CLS index). if not (offsets[token_start_index][0] <= start_char", "from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer", "and end positions for i, tokenized_example in enumerate(tokenized_examples): # Grab", "args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if", "out of the span (in which case this feature is", "if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"]", "that overlaps a bit the context of the previous feature.", "k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and", "os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get inner model", "forward(self, y, label): start_logits, end_logits = y start_position, end_position =", "(start_loss + end_loss) / 2 return loss def run(args): paddle.set_device(args.device)", "index of the answer in the text. start_char = answer_starts[0]", "num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform weight", "import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. #", "tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step %", "offset mappings will give us a map from token to", "import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import", "range(len(examples))] questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples =", "last offset if the answer is the last word (edge", "= 0 while sequence_ids[token_start_index] != 1: token_start_index += 1 #", "rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if", "text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != 1:", "# in one example possible giving several features when a", "when a context is long, each of those features having", "# Note: we could go after the last offset if", "num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps,", "= 0 tic_train = time.time() for epoch in range(num_train_epochs): for", "from paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers import", "end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss)", "end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits)", "all_end_logits = [] tic_eval = time.time() for batch in data_loader:", "import Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "context that overlaps a bit the context of the previous", "ArrowTable as basic data structure, while we use list of", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "(ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def", "that example (to know what is the context and what", "of the previous feature. # NOTE: Almost the same functionality", "pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds,", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "p in model.named_parameters() if not any(nd in n for nd", "paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower()", "# See the License for the specific language governing permissions", "time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data,", "batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor =", "= cls_index else: # Otherwise move the token_start_index and token_end_index", "1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return", "(global_step, epoch + 1, step + 1, loss, args.logging_steps /", "one example possible giving several features when a context is", "index of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index =", "paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower()", "tokenized_example['offset_mapping'] # Grab the sequence corresponding to that example (to", "ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args):", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "y start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position", "LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to", "self).__init__() def forward(self, y, label): start_logits, end_logits = y start_position,", "in the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index]", "# Set to None the offset_mapping that are not part", "the text. token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index", "open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4)", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "each of those features having a # context that overlaps", "Reserved. # Copyright 2018 The HuggingFace Inc. team. # #", "easy to determine if a token # position is part", "start_positions, end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss", "with the License. # You may obtain a copy of", "1000 == 0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits))", "part of the context so it's easy to determine if", "import random import time import json import math from functools", "1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type =", "args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model =", "\"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds,", "tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is", "shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\":", "while sequence_ids[token_start_index] != 1: token_start_index += 1 # End token", "index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char):", "1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions,", "batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps > 0", "\"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self):", "time.time() for epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader):", "== 0 or global_step == num_training_steps: if rank == 0:", "# limitations under the License. import os import random import", "input=end_logits, label=end_position) loss = (start_loss + end_loss) / 2 return", "write all_nbest_json and scores_diff_json files if needed with open('prediction.json', \"w\",", "Start/end character index of the answer in the text. start_char", "map from token to character position in the original context.", "pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader(", "def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank =", "= load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True)", "questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no", "compliance with the License. # You may obtain a copy", "np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits =", "agreed to in writing, software # distributed under the License", "is the context and what is the question). sequence_ids =", "the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the", "after the last offset if the answer is the last", "the example containing this span of text. sample_index = tokenized_example['overflow_to_sample']", "= [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions,", "The main difference is # that HugggingFace uses ArrowTable as", "distributed under the License is distributed on an \"AS IS\"", "# All bias and LayerNorm parameters are excluded. decay_params =", "load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler", "DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps", "== 0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time", "input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for", "We will label impossible answers with the index of the", "# help us compute the start_positions and end_positions. offsets =", "__init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits =", "end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position,", "in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) #", "to get inner model of DataParallel model_to_save = model._layers if", "previous feature. # NOTE: Almost the same functionality as HuggingFace's", "os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path)", "math from functools import partial import numpy as np import", "express or implied. # See the License for the specific", "index of the current span in the text. token_end_index =", "except in compliance with the License. # You may obtain", "tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label", "(start_positions, end_positions)) if global_step % args.logging_steps == 0: print( \"global", "the two ends of the answer. # Note: we could", "= os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) #", "sequence corresponding to that example (to know what is the", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "for nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler,", "not use this file except in compliance with the License.", "paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from", "# Generate parameter names needed to perform weight decay. #", "print(\"init checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if", "tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move", "writing, software # distributed under the License is distributed on", "questions = [examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer(", "CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The", "text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts']", "- tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if", "to character position in the original context. This will #", "sequence_ids = tokenized_example['token_type_ids'] # One example can give several spans,", "speed: %.2f step/s\" % (global_step, epoch + 1, step +", "you may not use this file except in compliance with", "fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps =", "n for nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW(", "= model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir)", "in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step += 1", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index +", "model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir)", "# NOTE: Almost the same functionality as HuggingFace's prepare_train_features function.", "= tokenized_example['token_type_ids'] # One example can give several spans, this", "if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\"", "<= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1", "if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples): #", "in model.named_parameters() if not any(nd in n for nd in", "= args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args)", "contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for i,", "to None the offset_mapping that are not part of the", "paddle.io import DataLoader from args import parse_args import paddlenlp as", "Inc. team. # # Licensed under the Apache License, Version", "dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ ==", "examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__()", "# Minus one more to reach actual text token_end_index -=", "position is part of the context or not. tokenized_examples[i][\"offset_mapping\"] =", "len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index -= 1", "data_loader, args): model.eval() all_start_logits = [] all_end_logits = [] tic_eval", "model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000", "any(nd in n for nd in [\"bias\", \"norm\"]) ] optimizer", "model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with", "nd in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon,", "paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets", "paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params)", "of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set", "json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False)", "tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the offset_mapping", "CONDITIONS OF ANY KIND, either express or implied. # See", "paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\":", "permissions and # limitations under the License. import os import", "set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from", "model of DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel)", "is part of the context or not. tokenized_examples[i][\"offset_mapping\"] = [", "context so it's easy to determine if a token #", "train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "(c) 2020 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018", "= answer_starts[0] end_char = start_char + len(answers[0]) # Start token", "_ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length)", "decay_params = [ p.name for n, p in model.named_parameters() if", "return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\": args =", "== 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path)", "1 # End token index of the current span in", "offset if the answer is the last word (edge case).", "time.time() for batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor,", "to reach actual text token_end_index -= 1 # Detect if", "start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss =", "for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0", "(ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed)", "context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] ==", "import numpy as np import paddle from paddle.io import DataLoader", "main difference is # that HugggingFace uses ArrowTable as basic", "(offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index", "else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler(", "token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1]", "super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits = y", "import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = {", "= MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0:", "= math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion)", "\"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda", "This will # help us compute the start_positions and end_positions.", "splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn", "% global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way", "is the index of the example containing this span of", "dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn =", "Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering,", "sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None", "_, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size,", "stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no need to", "if a token # position is part of the context", "None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if", "RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model,", "= [] all_end_logits = [] tic_eval = time.time() for batch", "tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ =", "start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while", "prepare_train_features function. The main difference is # that HugggingFace uses", "= token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index -=", "dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps >", "os.makedirs(output_dir) # need better way to get inner model of", "Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # Copyright", "args.max_answer_length) # Can also write all_nbest_json and scores_diff_json files if", "= start_char + len(answers[0]) # Start token index of the", "axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position)", "of the current span in the text. token_start_index = 0", "tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step == num_training_steps: break", "batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\":", "tic_eval = time.time() for batch in data_loader: input_ids, token_type_ids =", "is the question). sequence_ids = tokenized_example['token_type_ids'] # One example can", "+ 1, loss, args.logging_steps / (time.time() - tic_train))) tic_train =", "the index of the example containing this span of text.", "return tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file)", "= [examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question'] for", "OR CONDITIONS OF ANY KIND, either express or implied. #", "governing permissions and # limitations under the License. import os", "len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per 1000:', time.time()", "collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__ == \"__main__\": args", "batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions,", "for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride,", "the License is distributed on an \"AS IS\" BASIS, #", "# Copyright 2018 The HuggingFace Inc. team. # # Licensed", "in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions =", "the last offset if the answer is the last word", "of the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if", "\"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) +", "dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples,", "pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples)", "model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y,", "# Start token index of the current span in the", "text. token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index +=", "from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() >", "current span in the text. token_end_index = len(input_ids) - 1", "(RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def", "all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and", "0 else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps /", "context of the previous feature. # NOTE: Almost the same", "global_step % args.logging_steps == 0: print( \"global step %d, epoch:", "feature. # NOTE: Almost the same functionality as HuggingFace's prepare_train_features", "1 while sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus", "/ len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate", "random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits", "files if needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write(", "tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path):", "import parse_args import paddlenlp as ppnlp from paddlenlp.data import Pad,", "features when a context is long, each of those features", "tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples!", "this feature is labeled with the CLS index). if not", "1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] =", "paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits,", "answer is out of the span (in which case this", "if not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get", "[\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay,", "text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to", "is long, each of those features having a # context", "all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits),", "one more to reach actual text token_end_index -= 1 #", "while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index", "len(answers[0]) # Start token index of the current span in", "prepare_train_features(examples): # Tokenize our examples with truncation and maybe padding,", "= tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will", "Minus one more to reach actual text token_end_index -= 1", "(time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad()", "global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize our examples", "paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits = []", "those examples! for i, tokenized_example in enumerate(tokenized_examples): # We will", "parameter names needed to perform weight decay. # All bias", "= len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index -=", "indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer):", "law or agreed to in writing, software # distributed under", "end_logits = y start_position, end_position = label start_position = paddle.unsqueeze(start_position,", "index of the current span in the text. token_start_index =", "the text. start_char = answer_starts[0] end_char = start_char + len(answers[0])", "that HugggingFace uses ArrowTable as basic data structure, while we", "All bias and LayerNorm parameters are excluded. decay_params = [", "import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers", "train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples,", "%.2f step/s\" % (global_step, epoch + 1, step + 1,", "token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset", "loss, args.logging_steps / (time.time() - tic_train))) tic_train = time.time() loss.backward()", "paddlenlp as ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict", "None the offset_mapping that are not part of the context", "text. start_char = answer_starts[0] end_char = start_char + len(answers[0]) #", "encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\")", "lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\":", "as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate(", "excluded. decay_params = [ p.name for n, p in model.named_parameters()", "if global_step % args.save_steps == 0 or global_step == num_training_steps:", "RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction", "examples with truncation and maybe padding, but keep the overflows", "spans, this is the index of the example containing this", "keep the overflows using a stride. This results # in", "all_nbest_json and scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8')", "# We will label impossible answers with the index of", "== 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not", "token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx", "(edge case). while token_start_index < len(offsets) and offsets[ token_start_index][0] <=", "else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step", "span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] #", "o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank", "span in the text. token_end_index = len(input_ids) - 1 while", "which case this feature is labeled with the CLS index).", "that are not part of the context so it's easy", "optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0 or", "compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab", "start_positions and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence", "of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id)", "context is long, each of those features having a #", "move the token_start_index and token_end_index to the two ends of", "batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id),", "= lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id),", "Can also write all_nbest_json and scores_diff_json files if needed with", "@paddle.no_grad() def evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits", "# position is part of the context or not. tokenized_examples[i][\"offset_mapping\"]", "# Start/end character index of the answer in the text.", "may obtain a copy of the License at # #", "the answer is out of the span (in which case", "\"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader", "1 # Detect if the answer is out of the", "token_start_index = 0 while sequence_ids[token_start_index] != 1: token_start_index += 1", "= compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) #", "overflows using a stride. This results # in one example", "position in the original context. This will # help us", "offset_mapping that are not part of the context so it's", "and end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding", "Copyright 2018 The HuggingFace Inc. team. # # Licensed under", "stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for i, tokenized_example", "to that example (to know what is the context and", "0 and len(all_start_logits): print(\"Processing example: %d\" % len(all_start_logits)) print('time per", "containing this span of text. sample_index = tokenized_example['overflow_to_sample'] answers =", "class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label):", "label=end_position) loss = (start_loss + end_loss) / 2 return loss", "json import math from functools import partial import numpy as", "and maybe padding, but keep the overflows using a stride.", "train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler =", "epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step +=", "squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD,", "loss = (start_loss + end_loss) / 2 return loss def", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "parse_args import paddlenlp as ppnlp from paddlenlp.data import Pad, Stack,", "is labeled with the CLS index). if not (offsets[token_start_index][0] <=", "tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank ==", "help us compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping']", "num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" %", "[examples[i]['question'] for i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts,", "input_ids = tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings", "may not use this file except in compliance with the", "- 1 while sequence_ids[token_end_index] != 1: token_end_index -= 1 #", "parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD()", "global_step += 1 input_ids, token_type_ids, start_positions, end_positions = batch logits", "example possible giving several features when a context is long,", "output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir)", "same functionality as HuggingFace's prepare_train_features function. The main difference is", "for i in range(len(examples))] questions = [examples[i]['question'] for i in", "in one example possible giving several features when a context", "inner model of DataParallel model_to_save = model._layers if isinstance( model,", "= [] tic_eval = time.time() for batch in data_loader: input_ids,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "use list of dictionary instead. contexts = [examples[i]['context'] for i", "lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names", "args.logging_steps / (time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step()", "a token # position is part of the context or", "this file except in compliance with the License. # You", "= load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size,", "fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader,", "DataLoader from args import parse_args import paddlenlp as ppnlp from", "The offset mappings will give us a map from token", "from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer", "def evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits =", "args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed to perform", "in the original context. This will # help us compute", "are excluded. decay_params = [ p.name for n, p in", "token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps", "perform weight decay. # All bias and LayerNorm parameters are", "paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad", "DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model", "import json import math from functools import partial import numpy", "token_end_index -= 1 # Detect if the answer is out", "args.do_predict and rank == 0: if args.predict_file: dev_ds = load_dataset(task_name,", "decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time()", "need better way to get inner model of DataParallel model_to_save", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({", "= paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({", "checkpoint from %s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size()", "# # Licensed under the Apache License, Version 2.0 (the", "Almost the same functionality as HuggingFace's prepare_train_features function. The main", "model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step ==", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "- 1 while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"]", "token index of the current span in the text. token_end_index", "start_position, end_position = label start_position = paddle.unsqueeze(start_position, axis=-1) end_position =", "so it's easy to determine if a token # position", "samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples)", "% len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval =", "a bit the context of the previous feature. # NOTE:", "sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus one more", "import paddle from paddle.io import DataLoader from args import parse_args", "samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"),", "= time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps", "those features having a # context that overlaps a bit", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "label): start_logits, end_logits = y start_position, end_position = label start_position", "difference is # that HugggingFace uses ArrowTable as basic data", "else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader))", "1 input_ids, token_type_ids, start_positions, end_positions = batch logits = model(", "BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer)", "the span (in which case this feature is labeled with", "the current span in the text. token_end_index = len(input_ids) -", "args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train')", "# End token index of the current span in the", "team. # # Licensed under the Apache License, Version 2.0", "paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from", "args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer =", "HuggingFace Inc. team. # # Licensed under the Apache License,", "+= 1 input_ids, token_type_ids, start_positions, end_positions = batch logits =", "\"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need better", "while we use list of dictionary instead. contexts = [examples[i]['context']", "paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering,", "for i, tokenized_example in enumerate(tokenized_examples): # We will label impossible", "the context and what is the question). sequence_ids = tokenized_example['token_type_ids']", "token_start_index and token_end_index to the two ends of the answer.", "= model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def", "max_seq_len=args.max_seq_length) # For validation, there is no need to compute", "list of dictionary instead. contexts = [examples[i]['context'] for i in", "tic_train = time.time() for epoch in range(num_train_epochs): for step, batch", "% 1000 == 0 and len(all_start_logits): print(\"Processing example: %d\" %", "= paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss", "Otherwise move the token_start_index and token_end_index to the two ends", "in the text. token_start_index = 0 while sequence_ids[token_start_index] != 1:", "CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >=", "1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if args.do_train:", "fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader", "from token to character position in the original context. This", "the index of the CLS token. input_ids = tokenized_example[\"input_ids\"] cls_index", "optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x", "language governing permissions and # limitations under the License. import", "(in which case this feature is labeled with the CLS", "or global_step == num_training_steps: if rank == 0: output_dir =", "start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if", "to determine if a token # position is part of", "contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there is no need", "rank = paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class,", "global_step % args.save_steps == 0 or global_step == num_training_steps: if", "args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path)", "+ end_loss) / 2 return loss def run(args): paddle.set_device(args.device) if", "if args.do_train: if args.train_file: train_ds = load_dataset(task_name, data_files=args.train_file) else: train_ds", "train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0,", "if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step)", "index of the example containing this span of text. sample_index", "model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args):", "= examples[sample_index]['answer_starts'] # Start/end character index of the answer in", "containing this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] =", "step %d, epoch: %d, batch: %d, loss: %f, speed: %.2f", "of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts =", "loss: %f, speed: %.2f step/s\" % (global_step, epoch + 1,", "import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import", "= tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init", "Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn,", "train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds,", "the License. import os import random import time import json", "tokenized_example['token_type_ids'] # One example can give several spans, this is", "args.max_steps if args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs", "dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds,", "token_start_index += 1 # End token index of the current", "end_position = paddle.unsqueeze(end_position, axis=-1) start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss", "load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer),", "or implied. # See the License for the specific language", "while sequence_ids[token_end_index] != 1: token_end_index -= 1 # Minus one", "% args.save_steps == 0 or global_step == num_training_steps: if rank", "i in range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length)", "args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs =", "if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint", "0: print( \"global step %d, epoch: %d, batch: %d, loss:", "answer is the last word (edge case). while token_start_index <", "[ p.name for n, p in model.named_parameters() if not any(nd", "range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step += 1 input_ids,", "lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0 or global_step", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "\"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed)", "range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing", "= batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits,", "len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval = time.time()", "model( input_ids=input_ids, token_type_ids=token_type_ids) loss = criterion(logits, (start_positions, end_positions)) if global_step", "== 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "# Grab the sequence corresponding to that example (to know", "context and what is the question). sequence_ids = tokenized_example['token_type_ids'] #", "token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples", "mappings will give us a map from token to character", "[examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question'] for i", "CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for epoch in", "impossible answers with the index of the CLS token. input_ids", "# that HugggingFace uses ArrowTable as basic data structure, while", "* args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup(", "<= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"]", "from functools import partial import numpy as np import paddle", "of the example containing this span of text. sample_index =", "paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class =", "criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for", "if global_step % args.logging_steps == 0: print( \"global step %d,", "= paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with truncation", "(the \"License\"); # you may not use this file except", "}): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps", "isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:',", "= tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation, there", "# you may not use this file except in compliance", "uses ArrowTable as basic data structure, while we use list", "load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True)", "dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0,", "sequence_ids[token_start_index] != 1: token_start_index += 1 # End token index", "+= 1 # End token index of the current span", "{ \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer),", "and LayerNorm parameters are excluded. decay_params = [ p.name for", "from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES", "= LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter names needed", "positions for i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence", "def forward(self, y, label): start_logits, end_logits = y start_position, end_position", "len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler", "sequence_ids[k] == 1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"])", "partial import numpy as np import paddle from paddle.io import", "lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }):", "tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction(", "import math from functools import partial import numpy as np", "if args.max_steps > 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs", "y, label): start_logits, end_logits = y start_position, end_position = label", "us a map from token to character position in the", "for epoch in range(num_train_epochs): for step, batch in enumerate(train_data_loader): global_step", "model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples):", "the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] !=", "of the answer. # Note: we could go after the", "if the answer is the last word (edge case). while", "validation, there is no need to compute start and end", "args): model.eval() all_start_logits = [] all_end_logits = [] tic_eval =", "0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds =", "are not part of the context so it's easy to", "= examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of", "Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True)", "from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate, compute_prediction from", "= lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id)", "] return tokenized_examples if args.do_predict and rank == 0: if", "# # Unless required by applicable law or agreed to", "corresponding to that example (to know what is the context", "# Otherwise move the token_start_index and token_end_index to the two", "token # position is part of the context or not.", "label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1) start_loss", "of the current span in the text. token_end_index = len(input_ids)", "import time import json import math from functools import partial", "examples[sample_index]['id'] # Set to None the offset_mapping that are not", "fn=Dict({ \"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\":", "end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "character index of the answer in the text. start_char =", "% args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model", "case this feature is labeled with the CLS index). if", "as ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict from", "Version 2.0 (the \"License\"); # you may not use this", "# One example can give several spans, this is the", "weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step", "= batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in", "data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler =", "bias and LayerNorm parameters are excluded. decay_params = [ p.name", "as np import paddle from paddle.io import DataLoader from args", "preds=all_predictions, is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def", "of the context so it's easy to determine if a", "[] tic_eval = time.time() for batch in data_loader: input_ids, token_type_ids", "for batch in data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor", "ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering, RobertaTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed)", "0 tic_train = time.time() for epoch in range(num_train_epochs): for step,", "tokenized_example[\"input_ids\"] cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will give", "p.name for n, p in model.named_parameters() if not any(nd in", "current span in the text. token_start_index = 0 while sequence_ids[token_start_index]", "is the last word (edge case). while token_start_index < len(offsets)", "character position in the original context. This will # help", "= cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the", "1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples", "= examples[sample_index]['id'] # Set to None the offset_mapping that are", "need to compute start and end positions for i, tokenized_example", "of the span (in which case this feature is labeled", "structure, while we use list of dictionary instead. contexts =", "implied. # See the License for the specific language governing", "results # in one example possible giving several features when", "tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >= end_char: token_end_index", "under the Apache License, Version 2.0 (the \"License\"); # you", "0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint from %s\" % args.model_name_or_path) model", "= args.max_steps if args.max_steps > 0 else len( train_data_loader) *", "to perform weight decay. # All bias and LayerNorm parameters", "writer: writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data,", "to:', output_dir) if global_step == num_training_steps: break def prepare_validation_features(examples): #", ">= end_char: token_end_index -= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1", "For validation, there is no need to compute start and", "could go after the last offset if the answer is", "= { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering,", "cls_index else: # Otherwise move the token_start_index and token_end_index to", "end_positions)) if global_step % args.logging_steps == 0: print( \"global step", "of dictionary instead. contexts = [examples[i]['context'] for i in range(len(examples))]", "data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also", "using a stride. This results # in one example possible", "1 return tokenized_examples if args.do_train: if args.train_file: train_ds = load_dataset(task_name,", "by applicable law or agreed to in writing, software #", "epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion =", "task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type]", "if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name,", "apply_decay_param_fun=lambda x: x in decay_params) criterion = CrossEntropyLossForSQuAD() global_step =", "in decay_params) criterion = CrossEntropyLossForSQuAD() global_step = 0 tic_train =", "batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions", "while token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index", "possible giving several features when a context is long, each", "learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in decay_params) criterion", "tokenized_examples if args.do_predict and rank == 0: if args.predict_file: dev_ds", "end_positions. offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding to", "loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step % args.save_steps == 0", "print('Saving checkpoint to:', output_dir) if global_step == num_training_steps: break def", "} def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader,", "= CrossEntropyLossForSQuAD() global_step = 0 tic_train = time.time() for epoch", "will label impossible answers with the index of the CLS", "= time.time() for epoch in range(num_train_epochs): for step, batch in", "CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits,", "example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] answers", "step + 1, loss, args.logging_steps / (time.time() - tic_train))) tic_train", "go after the last offset if the answer is the", "the answer in the text. start_char = answer_starts[0] end_char =", "model.eval() all_start_logits = [] all_end_logits = [] tic_eval = time.time()", "paddle.DataParallel) else model model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if", "this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id']", "enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions, end_positions = batch", "All Rights Reserved. # Copyright 2018 The HuggingFace Inc. team.", "writer.write( json.dumps( all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions,", "the previous feature. # NOTE: Almost the same functionality as", "Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers", "= model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) %", "more to reach actual text token_end_index -= 1 # Detect", "tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1 else None)", "not any(nd in n for nd in [\"bias\", \"norm\"]) ]", "reach actual text token_end_index -= 1 # Detect if the", "and what is the question). sequence_ids = tokenized_example['token_type_ids'] # One", "example containing this span of text. sample_index = tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"]", "evaluate(model, data_loader, args): model.eval() all_start_logits = [] all_end_logits = []", "examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of the", "= time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _ = compute_prediction( data_loader.dataset.data,", "token index of the current span in the text. token_start_index", "= [ (o if sequence_ids[k] == 1 else None) for", "if sequence_ids[k] == 1 else None) for k, o in", "model_to_save = model._layers if isinstance( model, paddle.DataParallel) else model model_to_save.save_pretrained(output_dir)", "return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env()", "all_predictions, ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train()", "loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank", "contexts = [examples[i]['context'] for i in range(len(examples))] questions = [examples[i]['question']", "End token index of the current span in the text.", "last word (edge case). while token_start_index < len(offsets) and offsets[", "case). while token_start_index < len(offsets) and offsets[ token_start_index][0] <= start_char:", "scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8') as writer:", "or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1", "[] all_end_logits = [] tic_eval = time.time() for batch in", "> 1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our", "max_seq_len=args.max_seq_length) # Let's label those examples! for i, tokenized_example in", "input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us a map", "/ (time.time() - tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step()", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\":", "names needed to perform weight decay. # All bias and", "time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _,", "the original context. This will # help us compute the", "Unless required by applicable law or agreed to in writing,", "if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank() task_name =", "HugggingFace uses ArrowTable as basic data structure, while we use", "span of text. sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts", "epoch: %d, batch: %d, loss: %f, speed: %.2f step/s\" %", "instead. contexts = [examples[i]['context'] for i in range(len(examples))] questions =", "i, tokenized_example in enumerate(tokenized_examples): # We will label impossible answers", "the context of the previous feature. # NOTE: Almost the", "actual text token_end_index -= 1 # Detect if the answer", "to the two ends of the answer. # Note: we", "for i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding", "of DataParallel model_to_save = model._layers if isinstance( model, paddle.DataParallel) else", "= paddle.distributed.get_rank() task_name = args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class", "import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering,", "the specific language governing permissions and # limitations under the", "all_start_logits = [] all_end_logits = [] tic_eval = time.time() for", "us compute the start_positions and end_positions. offsets = tokenized_example['offset_mapping'] #", "and rank == 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file)", ">= end_char): tokenized_examples[i][\"start_positions\"] = cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: #", "if global_step == num_training_steps: break def prepare_validation_features(examples): # Tokenize our", "applicable law or agreed to in writing, software # distributed", "global_step == num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir,", "-= 1 # Minus one more to reach actual text", "HuggingFace's prepare_train_features function. The main difference is # that HugggingFace", "to compute start and end positions for i, tokenized_example in", "set_seed(args): random.seed(args.seed) np.random.seed(args.seed) paddle.seed(args.seed) @paddle.no_grad() def evaluate(model, data_loader, args): model.eval()", "ensure_ascii=False, indent=4) + \"\\n\") squad_evaluate( examples=data_loader.dataset.data, preds=all_predictions, is_whitespace_splited=False) model.train() class", "loss = criterion(logits, (start_positions, end_positions)) if global_step % args.logging_steps ==", "the offset_mapping that are not part of the context so", "will give us a map from token to character position", "several spans, this is the index of the example containing", "!= 1: token_start_index += 1 # End token index of", "and # limitations under the License. import os import random", "- tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx]) all_end_logits.append(end_logits_tensor.numpy()[idx]) all_predictions, _, _", "is # that HugggingFace uses ArrowTable as basic data structure,", "in writing, software # distributed under the License is distributed", "compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can", "# Let's label those examples! for i, tokenized_example in enumerate(tokenized_examples):", "if args.do_predict and rank == 0: if args.predict_file: dev_ds =", "= tokenized_example['overflow_to_sample'] tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the", "token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != 1: token_end_index", "range(len(examples))] tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For", "from paddle.io import DataLoader from args import parse_args import paddlenlp", "batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids) for idx in range(start_logits_tensor.shape[0]):", "not os.path.exists(output_dir): os.makedirs(output_dir) # need better way to get inner", "enumerate(tokenized_examples): # We will label impossible answers with the index", "in [\"bias\", \"norm\"]) ] optimizer = paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(),", "run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size() > 1: paddle.distributed.init_parallel_env() rank = paddle.distributed.get_rank()", "tokenized_examples[i][\"example_id\"] = examples[sample_index]['id'] # Set to None the offset_mapping that", "train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn =", "paddlenlp.metrics.squad import squad_evaluate, compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES =", "= (start_loss + end_loss) / 2 return loss def run(args):", "= DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if", "math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) #", "= args.task_name.lower() args.model_type = args.model_type.lower() model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer", "-= 1 tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if", "if needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps(", "token_type_ids) for idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 ==", "args.logging_steps == 0: print( \"global step %d, epoch: %d, batch:", "= DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "basic data structure, while we use list of dictionary instead.", "Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader(", "License, Version 2.0 (the \"License\"); # you may not use", "+= 1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >=", "paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize", "having a # context that overlaps a bit the context", "answers with the index of the CLS token. input_ids =", "offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index", "# You may obtain a copy of the License at", "model_class, tokenizer_class = MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank", "Generate parameter names needed to perform weight decay. # All", "ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup", "padding, but keep the overflows using a stride. This results", "0: output_dir = os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir):", "the context so it's easy to determine if a token", "part of the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o", "load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False)", "give us a map from token to character position in", "dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args)", "Tokenize our examples with truncation and maybe padding, but keep", "the context or not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k]", "span in the text. token_start_index = 0 while sequence_ids[token_start_index] !=", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "token_type_ids, start_positions, end_positions = batch logits = model( input_ids=input_ids, token_type_ids=token_type_ids)", "batch: %d, loss: %f, speed: %.2f step/s\" % (global_step, epoch", "dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features,", "\"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader =", "args.num_train_epochs num_train_epochs = math.ceil(num_training_steps / len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate,", "no need to compute start and end positions for i,", "1, step + 1, loss, args.logging_steps / (time.time() - tic_train)))", "MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\":", "else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler = paddle.io.BatchSampler(", "not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples[i][\"start_positions\"] =", "= token_end_index + 1 return tokenized_examples if args.do_train: if args.train_file:", "\"input_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\")", "paddle.DataParallel(model) def prepare_train_features(examples): # Tokenize our examples with truncation and", "len(all_start_logits) % 1000 == 0 and len(all_start_logits): print(\"Processing example: %d\"", "features having a # context that overlaps a bit the", "we use list of dictionary instead. contexts = [examples[i]['context'] for", "rank == 0: if args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else:", "question). sequence_ids = tokenized_example['token_type_ids'] # One example can give several", "with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions, ensure_ascii=False,", "answer_starts = examples[sample_index]['answer_starts'] # Start/end character index of the answer", "len(train_data_loader)) lr_scheduler = LinearDecayWithWarmup( args.learning_rate, num_training_steps, args.warmup_proportion) # Generate parameter", "args.save_steps == 0 or global_step == num_training_steps: if rank ==", "a context is long, each of those features having a", "step, batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids, start_positions,", "the sequence corresponding to that example (to know what is", "random import time import json import math from functools import", "== num_training_steps: if rank == 0: output_dir = os.path.join(args.output_dir, \"model_%d\"", "in enumerate(tokenized_examples): # Grab the sequence corresponding to that example", "the License for the specific language governing permissions and #", "giving several features when a context is long, each of", "BertTokenizer from paddlenlp.transformers import ErnieForQuestionAnswering, ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering,", "%d, batch: %d, loss: %f, speed: %.2f step/s\" % (global_step,", "%f, speed: %.2f step/s\" % (global_step, epoch + 1, step", "Apache License, Version 2.0 (the \"License\"); # you may not", "give several spans, this is the index of the example", "os.path.join(args.output_dir, \"model_%d\" % global_step) if not os.path.exists(output_dir): os.makedirs(output_dir) # need", "either express or implied. # See the License for the", "and scores_diff_json files if needed with open('prediction.json', \"w\", encoding='utf-8') as", "the overflows using a stride. This results # in one", "model_to_save.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) print('Saving checkpoint to:', output_dir) if global_step == num_training_steps:", "under the License. import os import random import time import", "Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from paddlenlp.transformers import", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "example (to know what is the context and what is", "token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"] = token_start_index -", "args.n_best_size, args.max_answer_length) # Can also write all_nbest_json and scores_diff_json files", "Pad(axis=0, pad_val=tokenizer.pad_token_id), \"token_type_ids\": Pad(axis=0, pad_val=tokenizer.pad_token_type_id), \"start_positions\": Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }):", "i, tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding to", "input_ids, token_type_ids, start_positions, end_positions = batch logits = model( input_ids=input_ids,", "paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\":", "evaluate(model, dev_data_loader, args) if __name__ == \"__main__\": args = parse_args()", "stride. This results # in one example possible giving several", "not. tokenized_examples[i][\"offset_mapping\"] = [ (o if sequence_ids[k] == 1 else", "%s\" % args.model_name_or_path) model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1:", "tokenized_examples = tokenizer( questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # For validation,", "len(offsets) and offsets[ token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples[i][\"start_positions\"]", "paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss + end_loss) / 2", "this is the index of the example containing this span", "examples[sample_index]['answer_starts'] # Start/end character index of the answer in the", "ErnieTokenizer from paddlenlp.transformers import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering,", "splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn", "numpy as np import paddle from paddle.io import DataLoader from", "batched=True) dev_batch_sampler = paddle.io.BatchSampler( dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda", "= label start_position = paddle.unsqueeze(start_position, axis=-1) end_position = paddle.unsqueeze(end_position, axis=-1)", "# context that overlaps a bit the context of the", "== 1 else None) for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ]", "paddle from paddle.io import DataLoader from args import parse_args import", "print('time per 1000:', time.time() - tic_eval) tic_eval = time.time() all_start_logits.append(start_logits_tensor.numpy()[idx])", "0 or global_step == num_training_steps: if rank == 0: output_dir", "we could go after the last offset if the answer", "is out of the span (in which case this feature", "the answer is the last word (edge case). while token_start_index", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "sample_index = tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] #", "the token_start_index and token_end_index to the two ends of the", "pad_val=tokenizer.pad_token_type_id) }): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True)", "import partial import numpy as np import paddle from paddle.io", "in enumerate(tokenized_examples): # We will label impossible answers with the", "offsets = tokenized_example['offset_mapping'] # Grab the sequence corresponding to that", "Start token index of the current span in the text.", "paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size, shuffle=True) train_batchify_fn = lambda samples, fn=Dict({ \"input_ids\":", "+ 1, step + 1, loss, args.logging_steps / (time.time() -", "tic_train))) tic_train = time.time() loss.backward() optimizer.step() lr_scheduler.step() optimizer.clear_grad() if global_step", "tokenized_example in enumerate(tokenized_examples): # Grab the sequence corresponding to that", "-= 1 # Detect if the answer is out of", "The HuggingFace Inc. team. # # Licensed under the Apache", "needed with open('prediction.json', \"w\", encoding='utf-8') as writer: writer.write( json.dumps( all_predictions,", "data structure, while we use list of dictionary instead. contexts", "questions, contexts, stride=args.doc_stride, max_seq_len=args.max_seq_length) # Let's label those examples! for", "answer in the text. start_char = answer_starts[0] end_char = start_char", "way to get inner model of DataParallel model_to_save = model._layers", "but keep the overflows using a stride. This results #", "data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev') dev_ds.map(prepare_validation_features, batched=True) dev_batch_sampler =", "> 0 else len( train_data_loader) * args.num_train_epochs num_train_epochs = math.ceil(num_training_steps", "of the answer in the text. start_char = answer_starts[0] end_char", "for k, o in enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict", "compute_prediction from paddlenlp.datasets import load_dataset MODEL_CLASSES = { \"bert\": (BertForQuestionAnswering,", "import ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers", "maybe padding, but keep the overflows using a stride. This", "start_char + len(answers[0]) # Start token index of the current", "+ 1 return tokenized_examples if args.do_train: if args.train_file: train_ds =", "1, loss, args.logging_steps / (time.time() - tic_train))) tic_train = time.time()", "train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps", "load_dataset(task_name, data_files=args.train_file) else: train_ds = load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler", "cls_index = input_ids.index(tokenizer.cls_token_id) # The offset mappings will give us", "RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp.metrics.squad import squad_evaluate,", "import os import random import time import json import math", "NOTE: Almost the same functionality as HuggingFace's prepare_train_features function. The", "[ (o if sequence_ids[k] == 1 else None) for k,", "dev_data_loader, args) if __name__ == \"__main__\": args = parse_args() run(args)", "start_loss = paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position)", "paddle.nn.functional.cross_entropy( input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss =", "input=start_logits, label=start_position) end_loss = paddle.nn.functional.cross_entropy( input=end_logits, label=end_position) loss = (start_loss", "= [ p.name for n, p in model.named_parameters() if not", "MODEL_CLASSES[args.model_type] tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if", "is_whitespace_splited=False) model.train() class CrossEntropyLossForSQuAD(paddle.nn.Layer): def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self,", "\"License\"); # you may not use this file except in", "can give several spans, this is the index of the", "ends of the answer. # Note: we could go after", "example can give several spans, this is the index of", "enumerate(tokenized_example[\"offset_mapping\"]) ] return tokenized_examples if args.do_predict and rank == 0:", "function. The main difference is # that HugggingFace uses ArrowTable", "import DataLoader from args import parse_args import paddlenlp as ppnlp", "(all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write all_nbest_json", "label impossible answers with the index of the CLS token.", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "dev_ds, batch_size=args.batch_size, shuffle=False) dev_batchify_fn = lambda samples, fn=Dict({ \"input_ids\": Pad(axis=0,", "= load_dataset(task_name, splits='train') train_ds.map(prepare_train_features, batched=True) train_batch_sampler = paddle.io.DistributedBatchSampler( train_ds, batch_size=args.batch_size,", "print( \"global step %d, epoch: %d, batch: %d, loss: %f,", "return tokenized_examples if args.do_predict and rank == 0: if args.predict_file:", "epoch + 1, step + 1, loss, args.logging_steps / (time.time()", "data_loader.dataset.new_data, (all_start_logits, all_end_logits), False, args.n_best_size, args.max_answer_length) # Can also write", "os import random import time import json import math from", "# distributed under the License is distributed on an \"AS", "Let's label those examples! for i, tokenized_example in enumerate(tokenized_examples): #", "2020 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The", "end positions for i, tokenized_example in enumerate(tokenized_examples): # Grab the", "for step, batch in enumerate(train_data_loader): global_step += 1 input_ids, token_type_ids,", "# Unless required by applicable law or agreed to in", "for n, p in model.named_parameters() if not any(nd in n", "def prepare_train_features(examples): # Tokenize our examples with truncation and maybe", "\"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler, collate_fn=train_batchify_fn,", "n, p in model.named_parameters() if not any(nd in n for", "truncation and maybe padding, but keep the overflows using a", "prepare_validation_features(examples): # Tokenize our examples with truncation and maybe padding,", "data_loader: input_ids, token_type_ids = batch start_logits_tensor, end_logits_tensor = model(input_ids, token_type_ids)", "(BertForQuestionAnswering, BertTokenizer), \"ernie\": (ErnieForQuestionAnswering, ErnieTokenizer), \"ernie_gram\": (ErnieGramForQuestionAnswering, ErnieGramTokenizer), \"roberta\": (RobertaForQuestionAnswering,", "One example can give several spans, this is the index", "%d\" % len(all_start_logits)) print('time per 1000:', time.time() - tic_eval) tic_eval", "answer_starts[0] end_char = start_char + len(answers[0]) # Start token index", "cls_index tokenized_examples[i][\"end_positions\"] = cls_index else: # Otherwise move the token_start_index", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "tokenized_examples[i][\"end_positions\"] = token_end_index + 1 return tokenized_examples if args.do_train: if", "token_end_index + 1 return tokenized_examples if args.do_train: if args.train_file: train_ds", "%d, loss: %f, speed: %.2f step/s\" % (global_step, epoch +", "it's easy to determine if a token # position is", "= paddle.optimizer.AdamW( learning_rate=lr_scheduler, epsilon=args.adam_epsilon, parameters=model.parameters(), weight_decay=args.weight_decay, apply_decay_param_fun=lambda x: x in", "idx in range(start_logits_tensor.shape[0]): if len(all_start_logits) % 1000 == 0 and", "tokenized_example in enumerate(tokenized_examples): # We will label impossible answers with", "You may obtain a copy of the License at #", "the CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1]", "1 # Minus one more to reach actual text token_end_index", "def __init__(self): super(CrossEntropyLossForSQuAD, self).__init__() def forward(self, y, label): start_logits, end_logits", "bit the context of the previous feature. # NOTE: Almost", "in the text. start_char = answer_starts[0] end_char = start_char +", "args.predict_file: dev_ds = load_dataset(task_name, data_files=args.predict_file) else: dev_ds = load_dataset(task_name, splits='dev')", "with truncation and maybe padding, but keep the overflows using", "of those features having a # context that overlaps a", "determine if a token # position is part of the", "tokenized_example['overflow_to_sample'] answers = examples[sample_index]['answers'] answer_starts = examples[sample_index]['answer_starts'] # Start/end character", "Note: we could go after the last offset if the", "tokenizer_class.from_pretrained(args.model_name_or_path) set_seed(args) if rank == 0: if os.path.exists(args.model_name_or_path): print(\"init checkpoint", "}): fn(samples) dev_data_loader = DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model,", "DataLoader( dataset=dev_ds, batch_sampler=dev_batch_sampler, collate_fn=dev_batchify_fn, return_list=True) evaluate(model, dev_data_loader, args) if __name__", "examples! for i, tokenized_example in enumerate(tokenized_examples): # We will label", "ErnieGramForQuestionAnswering, ErnieGramTokenizer from paddlenlp.transformers import RobertaForQuestionAnswering, RobertaTokenizer from paddlenlp.transformers import", "start_char = answer_starts[0] end_char = start_char + len(answers[0]) # Start", "word (edge case). while token_start_index < len(offsets) and offsets[ token_start_index][0]", "if not any(nd in n for nd in [\"bias\", \"norm\"])", "will # help us compute the start_positions and end_positions. offsets", "the Apache License, Version 2.0 (the \"License\"); # you may", "ppnlp from paddlenlp.data import Pad, Stack, Tuple, Dict from paddlenlp.transformers", "all_predictions, _, _ = compute_prediction( data_loader.dataset.data, data_loader.dataset.new_data, (all_start_logits, all_end_logits), False,", "Pad, Stack, Tuple, Dict from paddlenlp.transformers import BertForQuestionAnswering, BertTokenizer from", "context. This will # help us compute the start_positions and", "!= 1: token_end_index -= 1 # Minus one more to", "end_loss) / 2 return loss def run(args): paddle.set_device(args.device) if paddle.distributed.get_world_size()", "np import paddle from paddle.io import DataLoader from args import", "label those examples! for i, tokenized_example in enumerate(tokenized_examples): # We", "collate_fn=train_batchify_fn, return_list=True) num_training_steps = args.max_steps if args.max_steps > 0 else", "Stack(dtype=\"int64\"), \"end_positions\": Stack(dtype=\"int64\") }): fn(samples) train_data_loader = DataLoader( dataset=train_ds, batch_sampler=train_batch_sampler,", "functools import partial import numpy as np import paddle from", "better way to get inner model of DataParallel model_to_save =", "model.named_parameters() if not any(nd in n for nd in [\"bias\",", "needed to perform weight decay. # All bias and LayerNorm", "1 tokenized_examples[i][\"start_positions\"] = token_start_index - 1 while offsets[token_end_index][1] >= end_char:", "model = model_class.from_pretrained(args.model_name_or_path) if paddle.distributed.get_world_size() > 1: model = paddle.DataParallel(model)" ]
[ "noise, it is epsilon-greedy with epsilon decreasing over time #", "every a available at a state Qout = tf.matmul(input1, W)", "axis=1) # Feature vector for next state representation nextQ =", "s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s:", "# TRAIN THE NETWORK init = tf.global_variables_initializer() # Set learning", "as tf import numpy as np import matplotlib.pyplot as plt", "tf.global_variables_initializer() # Set learning parameters y = 0.99 e =", "< e: a[0] = env.action_space.sample() s1, r, d, _ =", "TABULAR IMPLEMENTATION # # # Set learning parameters # lr", "W vector in range 0 - 0.01 (like the way", "# Choose action by epsilon (e) greedy # print(\"s =", "network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ", "Choose action by epsilon (e) greedy # print(\"s = \",", "greedily (with noise) picking from Q table # # Because", "loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel", "print(\"Episode #{} is running!\".format(i)) # First state s = env.reset()", "= tf.global_variables_initializer() # Set learning parameters y = 0.99 e", "= 0.1 number_episodes = 2000 # List to store total", "j < 200: # or While not d: j +=", "maxQ1 # Train our network using target and predicted Q", "W is the actual Q value a, allQ = sess.run([predict,", "0.]] # Identity [s:s+1] is a one-hot vector # Therefore", "= tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout", "[] with tf.Session() as sess: sess.run(init) for i in range(number_episodes):", "(with noise) picking from Q table # # Because of", "s = env.reset() rAll = 0 d = False j", "lr * (r + y * np.max(Q[s1, :]) - Q[s,", "for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) #", "jList = [] rList = [] with tf.Session() as sess:", "rList = [] # for i in range (number_episodes): #", "Q value by feeding the new state throughout the network", "= tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0,", "d: e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close()", "per episode # rList = [] # for i in", "s = env.reset() # rAll = 0 # d =", "# Because of the noise, it is epsilon-greedy with epsilon", "at a state predict = tf.argmax(Qout, axis=1) # Feature vector", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss", "# Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of", "--> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 -->", "e: a[0] = env.action_space.sample() s1, r, d, _ = env.step(a[0])", "Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # #", "r, d, _ = env.step(a[0]) # Obtain next state Q", "env.action_space.n)*(1./(i + 1))) # s1, r, d, _ = env.step(a)", "network while j < 200: # or While not d:", "import gym import tensorflow as tf import numpy as np", "reward and steps per episode # rList = [] #", "# Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer =", "not d: j += 1 # Choose action by epsilon", "tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector", "tf.Session() as sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{}", "+ 1: [[0. 1. 0. 0. 0. 0. 0. 0.", "0. 0. 0. 0. 0. 0.]] # s = 1", "Greedy action at a state predict = tf.argmax(Qout, axis=1) #", "False # j = 0 # while j < 99:", "Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward", "< 200: # or While not d: j += 1", "and steps per episode # rList = [] # for", "# Credit to https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf", "name=None) # Weighting W vector in range 0 - 0.01", "0.95 # number_episodes = 20000 # # # Initial table", "TRAIN THE NETWORK init = tf.global_variables_initializer() # Set learning parameters", "* (r + y * np.max(Q[s1, :]) - Q[s, a])", "Set learning parameters # lr = 0.8 # y =", "\", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s =", "tf.matmul(input1, W) # Greedy action at a state predict =", "in range 0 - 0.01 (like the way Andrew Ng", "--> Identity s: s + 1: [[0. 1. 0. 0.", "sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{} is running!\".format(i))", "0.01)) # Qout with shape [1, env.action_space.n] - Action state", "actual Q value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]})", "THE NETWORK init = tf.global_variables_initializer() # Set learning parameters y", "s = s1 # if d: # break # rList.append(rAll)", "vector # Therefore W is the actual Q value a,", "d, _ = env.step(a[0]) # Obtain next state Q value", "epsilon decreasing over time # a = np.argmax(Q[s, :] +", "1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return", "--> Identity s: s + 1: [[1. 0. 0. 0.", "= tf.matmul(input1, W) # Greedy action at a state predict", "nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss =", "+ 1: [[1. 0. 0. 0. 0. 0. 0. 0.", "= Q[s, a] + lr * (r + y *", "# Feature vector for current state representation input1 = tf.placeholder(shape=[1,", "a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) #", "is a one-hot vector # Therefore W is the actual", "*0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with", "value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1)", "dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer", "= 0 # d = False # j = 0", "plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps", "# or While not d: j += 1 # Choose", "# Weighting W vector in range 0 - 0.01 (like", "= False j = 0 # Q network while j", "input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape,", "epsilon-greedy with epsilon decreasing over time # a = np.argmax(Q[s,", "+= 1 # # Choose an action by greedily (with", "numpy as np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0')", "# s1, r, d, _ = env.step(a) # # env.render()", ":] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d,", "state predict = tf.argmax(Qout, axis=1) # Feature vector for next", "trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer() # Set", "Identity s: s + 1: [[1. 0. 0. 0. 0.", "rAll = 0 # d = False # j =", "allQ targetQ[0, a[0]] = r + y * maxQ1 #", "= trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer() #", "Qout = tf.matmul(input1, W) # Greedy action at a state", "# # Initial table with all zeros # Q =", "# y = 0.95 # number_episodes = 20000 # #", "is the actual Q value a, allQ = sess.run([predict, Qout],", "feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample() s1,", "targetQ[0, a[0]] = r + y * maxQ1 # Train", "While not d: j += 1 # Choose action by", "0. 0. 0. 0. 0.]] # s = 1 -->", "greedy # print(\"s = \", s,\" --> Identity s:s+1: \",", "Obtain next state Q value by feeding the new state", "= r + y * maxQ1 # Train our network", "tf.argmax(Qout, axis=1) # Feature vector for next state representation nextQ", "to store total rewards and steps per episode jList =", "_ = env.step(a) # # env.render() # # # Update", "+ lr * (r + y * np.max(Q[s1, :]) -", "= 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList,", "(r + y * np.max(Q[s1, :]) - Q[s, a]) #", "table with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) #", "# # Set learning parameters # lr = 0.8 #", "List to store total rewards and steps per episode jList", "with epsilon decreasing over time # a = np.argmax(Q[s, :]", "steps per episode # rList = [] # for i", "Q values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ:", "- Q[s, a]) # rAll += r # s =", "sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] =", "0.01 (like the way Andrew Ng did with *0.01 W", "0.]] # s = 1 --> Identity s: s +", "and predicted Q values _, W1 = sess.run([updateModel, W], feed_dict={input1:", "= sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ", "IMPLEMENTATION # # # Set learning parameters # lr =", "Choose an action by greedily (with noise) picking from Q", "a[0] = env.action_space.sample() s1, r, d, _ = env.step(a[0]) #", "# s = env.reset() # rAll = 0 # d", "Set learning parameters y = 0.99 e = 0.1 number_episodes", "Action state value for Q[s, a] with every a available", "0. 0.]] # s = 1 --> Identity s: s", "env.step(a[0]) # Obtain next state Q value by feeding the", "by greedily (with noise) picking from Q table # #", "# Feature vector for next state representation nextQ = tf.placeholder(shape=[1,", "[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "s = 1 --> Identity s: s + 1: [[0.", "= np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and", "# # Because of the noise, it is epsilon-greedy with", "is running!\".format(i)) # s = env.reset() # rAll = 0", "plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # -------------------------------------------------------------------------", "# rList = [] # for i in range (number_episodes):", "j = 0 # while j < 99: # j", "tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape [1, env.action_space.n]", "[1, env.action_space.n] - Action state value for Q[s, a] with", "learning parameters # lr = 0.8 # y = 0.95", "nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE", "0. 0. 0. 0.]] # s = 1 --> Identity", "# # # Initial table with all zeros # Q", "vector for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32)", "= [] with tf.Session() as sess: sess.run(init) for i in", "= env.reset() rAll = 0 d = False j =", "s1 if d: e = 1./((i/50) + 10) break jList.append(j)", "new state throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]})", "current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>,", "representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) #", "NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state", "print(\"Episode #{} is running!\".format(i)) # s = env.reset() # rAll", "0 # d = False # j = 0 #", "maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector in range", "and steps per episode jList = [] rList = []", "# # # List of reward and steps per episode", "0 # while j < 99: # j += 1", "False j = 0 # Q network while j <", "# print(\"Episode #{} is running!\".format(i)) # s = env.reset() #", "0 - 0.01 (like the way Andrew Ng did with", "or While not d: j += 1 # Choose action", "dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None,", "2000 # List to store total rewards and steps per", "state Qout = tf.matmul(input1, W) # Greedy action at a", "predicted Q values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1],", "import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK", "if d: e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll)", "np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL", "s: s + 1: [[0. 1. 0. 0. 0. 0.", "label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION", "= env.action_space.sample() s1, r, d, _ = env.step(a[0]) # Obtain", "new knowledge # Q[s, a] = Q[s, a] + lr", "np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] =", "= sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r", "s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0", "env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ))", "i in range (number_episodes): # print(\"Episode #{} is running!\".format(i)) #", "# j = 0 # while j < 99: #", "import tensorflow as tf import numpy as np import matplotlib.pyplot", "Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show()", "= env.reset() # rAll = 0 # d = False", "plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() #", "# tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W", "the new state throughout the network Q1 = sess.run(Qout, feed_dict={input1:", "- 0.01 (like the way Andrew Ng did with *0.01", "# Therefore W is the actual Q value a, allQ", "the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1)", "1. 0. 0. 0. 0. 0. 0. 0. 0. 0.", "tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None,", "j = 0 # Q network while j < 200:", "with every a available at a state Qout = tf.matmul(input1,", "the way Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n,", "state Q value by feeding the new state throughout the", "value by feeding the new state throughout the network Q1", "env.step(a) # # env.render() # # # Update Q table", "# Set learning parameters y = 0.99 e = 0.1", "a]) # rAll += r # s = s1 #", "in range (number_episodes): # print(\"Episode #{} is running!\".format(i)) # s", "0, 0.01)) # Qout with shape [1, env.action_space.n] - Action", "0.99 e = 0.1 number_episodes = 2000 # List to", "by feeding the new state throughout the network Q1 =", "Q network while j < 200: # or While not", "= tf.argmax(Qout, axis=1) # Feature vector for next state representation", "First state s = env.reset() rAll = 0 d =", "Because of the noise, it is epsilon-greedy with epsilon decreasing", "as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph()", "picking from Q table # # Because of the noise,", "1: [[0. 1. 0. 0. 0. 0. 0. 0. 0.", "# Obtain next state Q value by feeding the new", "plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR", "number_episodes = 20000 # # # Initial table with all", "= 0 d = False j = 0 # Q", "- Q Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION #", "= tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init", "# TABULAR IMPLEMENTATION # # # Set learning parameters #", "# Set learning parameters # lr = 0.8 # y", "r + y * maxQ1 # Train our network using", "= 0 # while j < 99: # j +=", "all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # # #", "is running!\".format(i)) # First state s = env.reset() rAll =", "noise) picking from Q table # # Because of the", "# Train our network using target and predicted Q values", "s + 1: [[0. 1. 0. 0. 0. 0. 0.", "# # Choose an action by greedily (with noise) picking", "= np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1,", "a available at a state Qout = tf.matmul(input1, W) #", "with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # #", "trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK", "# ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set learning", "updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init = tf.global_variables_initializer()", "minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting W vector in", "e = 1./((i/50) + 10) break jList.append(j) rList.append(rAll) env.close() plt.figure()", "name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) # Weighting", "= 20000 # # # Initial table with all zeros", "# Choose an action by greedily (with noise) picking from", "+= 1 # Choose action by epsilon (e) greedy #", "1 # Choose action by epsilon (e) greedy # print(\"s", "np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r,", "the actual Q value a, allQ = sess.run([predict, Qout], feed_dict={input1:", "# # # Set learning parameters # lr = 0.8", "at a state Qout = tf.matmul(input1, W) # Greedy action", "0 --> Identity s: s + 1: [[1. 0. 0.", "0. 0. 0.]] # Identity [s:s+1] is a one-hot vector", "Initial table with all zeros # Q = np.zeros([env.observation_space.n, env.action_space.n])", "< 99: # j += 1 # # Choose an", "j < 99: # j += 1 # # Choose", "# s = 1 --> Identity s: s + 1:", "# s = s1 # if d: # break #", "Q[s, a] with every a available at a state Qout", "# First state s = env.reset() rAll = 0 d", "for i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First", "d = False # j = 0 # while j", "range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state s =", "store total rewards and steps per episode jList = []", "one-hot vector # Therefore W is the actual Q value", "network using target and predicted Q values _, W1 =", "# Identity [s:s+1] is a one-hot vector # Therefore W", "_, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll", "with new knowledge # Q[s, a] = Q[s, a] +", "= sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0]", "steps per episode jList = [] rList = [] with", "1 # # Choose an action by greedily (with noise)", "+ y * np.max(Q[s1, :]) - Q[s, a]) # rAll", "feeding the new state throughout the network Q1 = sess.run(Qout,", "rAll += r s = s1 if d: e =", "W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape", "to https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf import numpy", "0 # Q network while j < 200: # or", "d: j += 1 # Choose action by epsilon (e)", "in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state s", "env.action_space.n] - Action state value for Q[s, a] with every", "np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d, _ =", "of reward and steps per episode # rList = []", "knowledge # Q[s, a] = Q[s, a] + lr *", "gym import tensorflow as tf import numpy as np import", "Weighting W vector in range 0 - 0.01 (like the", "= 2000 # List to store total rewards and steps", "= env.step(a[0]) # Obtain next state Q value by feeding", "lr = 0.8 # y = 0.95 # number_episodes =", "state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>)", "np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r + y", "= [] # for i in range (number_episodes): # print(\"Episode", "= \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s", "state throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1", "epsilon (e) greedy # print(\"s = \", s,\" --> Identity", "s1, r, d, _ = env.step(a[0]) # Obtain next state", "plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set", "with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout", "for i in range (number_episodes): # print(\"Episode #{} is running!\".format(i))", "20000 # # # Initial table with all zeros #", "range (number_episodes): # print(\"Episode #{} is running!\".format(i)) # s =", "time # a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i +", "Q[s, a] = Q[s, a] + lr * (r +", "# print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1])", "a] + lr * (r + y * np.max(Q[s1, :])", "0.1 number_episodes = 2000 # List to store total rewards", "np.max(Q[s1, :]) - Q[s, a]) # rAll += r #", "available at a state Qout = tf.matmul(input1, W) # Greedy", "Feature vector for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n],", "+ 10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return -", "values _, W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ})", "# rAll += r # s = s1 # if", "List of reward and steps per episode # rList =", "0. 0.]] # Identity [s:s+1] is a one-hot vector #", "action by greedily (with noise) picking from Q table #", "= 0 --> Identity s: s + 1: [[1. 0.", "a] = Q[s, a] + lr * (r + y", "# number_episodes = 20000 # # # Initial table with", "Learning\") plt.show() # ------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # #", "with shape [1, env.action_space.n] - Action state value for Q[s,", "matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION", "total rewards and steps per episode jList = [] rList", "an action by greedily (with noise) picking from Q table", "targetQ = allQ targetQ[0, a[0]] = r + y *", "------------------------------------------------------------------------- # TABULAR IMPLEMENTATION # # # Set learning parameters", "y = 0.95 # number_episodes = 20000 # # #", "representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss", "1: [[1. 0. 0. 0. 0. 0. 0. 0. 0.", "rAll = 0 d = False j = 0 #", "sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0,", "+ np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r, d, _", "r, d, _ = env.step(a) # # env.render() # #", "Q table # # Because of the noise, it is", "# j += 1 # # Choose an action by", "our network using target and predicted Q values _, W1", "tf.reset_default_graph() # Feature vector for current state representation input1 =", "y = 0.99 e = 0.1 number_episodes = 2000 #", "predict = tf.argmax(Qout, axis=1) # Feature vector for next state", "# d = False # j = 0 # while", "as np import matplotlib.pyplot as plt env = gym.make('FrozenLake-v0') #", "Q[s, a]) # rAll += r # s = s1", "# Q network while j < 200: # or While", "# # env.render() # # # Update Q table with", "= tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) # Qout with shape [1,", "as sess: sess.run(init) for i in range(number_episodes): print(\"Episode #{} is", "_ = env.step(a[0]) # Obtain next state Q value by", "state s = env.reset() rAll = 0 d = False", "NETWORK init = tf.global_variables_initializer() # Set learning parameters y =", "NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state representation", "# while j < 99: # j += 1 #", "parameters # lr = 0.8 # y = 0.95 #", "vector for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32)", "a one-hot vector # Therefore W is the actual Q", "throughout the network Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 =", "s1, r, d, _ = env.step(a) # # env.render() #", "# a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1)))", "# for i in range (number_episodes): # print(\"Episode #{} is", "d = False j = 0 # Q network while", "# Q[s, a] = Q[s, a] + lr * (r", "value for Q[s, a] with every a available at a", "it is epsilon-greedy with epsilon decreasing over time # a", "seed=None, name=None) # Weighting W vector in range 0 -", "IMPLEMENTATION tf.reset_default_graph() # Feature vector for current state representation input1", "[] # for i in range (number_episodes): # print(\"Episode #{}", "vector in range 0 - 0.01 (like the way Andrew", "using target and predicted Q values _, W1 = sess.run([updateModel,", "y * np.max(Q[s1, :]) - Q[s, a]) # rAll +=", "0. 0. 0. 0. 0. 0. 0. 0. 0.]] #", "# # # Update Q table with new knowledge #", "Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e: a[0] = env.action_space.sample()", "rAll += r # s = s1 # if d:", "state value for Q[s, a] with every a available at", "parameters y = 0.99 e = 0.1 number_episodes = 2000", "r # s = s1 # if d: # break", "tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN THE NETWORK init =", "[] rList = [] with tf.Session() as sess: sess.run(init) for", "range 0 - 0.01 (like the way Andrew Ng did", "# Initial table with all zeros # Q = np.zeros([env.observation_space.n,", "# s = 0 --> Identity s: s + 1:", "Update Q table with new knowledge # Q[s, a] =", "plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() # ------------------------------------------------------------------------- #", "for Q[s, a] with every a available at a state", "rewards and steps per episode jList = [] rList =", "env = gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature", "(like the way Andrew Ng did with *0.01 W =", "s = 0 --> Identity s: s + 1: [[1.", "j += 1 # Choose action by epsilon (e) greedy", "import numpy as np import matplotlib.pyplot as plt env =", "zeros # Q = np.zeros([env.observation_space.n, env.action_space.n]) # # # List", "of the noise, it is epsilon-greedy with epsilon decreasing over", "gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for", "0. 0. 0. 0.]] # Identity [s:s+1] is a one-hot", "0. 0. 0. 0. 0. 0. 0.]] # Identity [s:s+1]", "feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]]", "Identity [s:s+1] is a one-hot vector # Therefore W is", "# # List of reward and steps per episode #", "action by epsilon (e) greedy # print(\"s = \", s,\"", "200: # or While not d: j += 1 #", "# Qout with shape [1, env.action_space.n] - Action state value", "# rAll = 0 # d = False # j", "a state Qout = tf.matmul(input1, W) # Greedy action at", "0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]", "0. 0. 0. 0. 0.]] # Identity [s:s+1] is a", "= gym.make('FrozenLake-v0') # NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector", "np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i + 1))) # s1, r,", "i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) # First state", "while j < 99: # j += 1 # #", "+= r # s = s1 # if d: #", "Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity", "sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s", "np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s = s1 if", "s = s1 if d: e = 1./((i/50) + 10)", "# List to store total rewards and steps per episode", "rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure()", "+ 1))) # s1, r, d, _ = env.step(a) #", "= 0.99 e = 0.1 number_episodes = 2000 # List", "with tf.Session() as sess: sess.run(init) for i in range(number_episodes): print(\"Episode", "np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s: s +", "10) break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q", "env.action_space.n]) # # # List of reward and steps per", "decreasing over time # a = np.argmax(Q[s, :] + np.random.rand(1,", "running!\".format(i)) # First state s = env.reset() rAll = 0", "#{} is running!\".format(i)) # s = env.reset() # rAll =", "from Q table # # Because of the noise, it", "Q1 = sess.run(Qout, feed_dict={input1: np.identity(env.observation_space.n)[s1:s1+1]}) maxQ1 = np.max(Q1) targetQ =", "number_episodes = 2000 # List to store total rewards and", "#{} is running!\".format(i)) # First state s = env.reset() rAll", "tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy loss loss = tf.reduce_sum(tf.square(Qout -", "= env.step(a) # # env.render() # # # Update Q", "# lr = 0.8 # y = 0.95 # number_episodes", "env.action_space.sample() s1, r, d, _ = env.step(a[0]) # Obtain next", "0 d = False j = 0 # Q network", "np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r, d, _", "= np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r +", "episode jList = [] rList = [] with tf.Session() as", "jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show()", "= 0.8 # y = 0.95 # number_episodes = 20000", "0. 0. 0. 0. 0. 0. 0. 0.]] # Identity", "next state Q value by feeding the new state throughout", "0. 0. 0. 0. 0. 0. 0.]] # s =", "Entropy loss loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1)", "# tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None)", "loss = tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel =", "env.render() # # # Update Q table with new knowledge", "# Greedy action at a state predict = tf.argmax(Qout, axis=1)", "# env.render() # # # Update Q table with new", "tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) #", "Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0,", "# # Update Q table with new knowledge # Q[s,", "Credit to https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf import", "= False # j = 0 # while j <", "# List of reward and steps per episode # rList", "while j < 200: # or While not d: j", "+= r s = s1 if d: e = 1./((i/50)", "* maxQ1 # Train our network using target and predicted", "0. 0. 0.]] # s = 1 --> Identity s:", "shape [1, env.action_space.n] - Action state value for Q[s, a]", "a state predict = tf.argmax(Qout, axis=1) # Feature vector for", "s: s + 1: [[1. 0. 0. 0. 0. 0.", "a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) <", "\", np.identity(env.observation_space.n)[s:s+1]) # s = 0 --> Identity s: s", "print(\"s = \", s,\" --> Identity s:s+1: \", np.identity(env.observation_space.n)[s:s+1]) #", "a[0]] = r + y * maxQ1 # Train our", "plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps -", "table # # Because of the noise, it is epsilon-greedy", "env.reset() rAll = 0 d = False j = 0", "maxQ1 = np.max(Q1) targetQ = allQ targetQ[0, a[0]] = r", "dtype=tf.float32, seed=None, name=None) # Weighting W vector in range 0", "np.zeros([env.observation_space.n, env.action_space.n]) # # # List of reward and steps", "break jList.append(j) rList.append(rAll) env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\")", "target and predicted Q values _, W1 = sess.run([updateModel, W],", "rList = [] with tf.Session() as sess: sess.run(init) for i", "running!\".format(i)) # s = env.reset() # rAll = 0 #", "Train our network using target and predicted Q values _,", "Identity s: s + 1: [[0. 1. 0. 0. 0.", "= s1 if d: e = 1./((i/50) + 10) break", "- Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\")", "allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if np.random.rand(1) < e:", "nextQ: targetQ}) rAll += r s = s1 if d:", "e = 0.1 number_episodes = 2000 # List to store", "[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.", "over time # a = np.argmax(Q[s, :] + np.random.rand(1, env.action_space.n)*(1./(i", "way Andrew Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n],", "Q value a, allQ = sess.run([predict, Qout], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1]}) if", "targetQ}) rAll += r s = s1 if d: e", "label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q", "Ng did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01))", "env.reset() # rAll = 0 # d = False #", "episode # rList = [] # for i in range", "sess.run(init) for i in range(number_episodes): print(\"Episode #{} is running!\".format(i)) #", "(e) greedy # print(\"s = \", s,\" --> Identity s:s+1:", "for current state representation input1 = tf.placeholder(shape=[1, env.observation_space.n], dtype=tf.float32) #", "Therefore W is the actual Q value a, allQ =", "feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s = s1", "99: # j += 1 # # Choose an action", "+ y * maxQ1 # Train our network using target", "by epsilon (e) greedy # print(\"s = \", s,\" -->", ":]) - Q[s, a]) # rAll += r # s", "r s = s1 if d: e = 1./((i/50) +", "= 1 --> Identity s: s + 1: [[0. 1.", "env.observation_space.n], dtype=tf.float32) # tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32,", "y * maxQ1 # Train our network using target and", "= 0.95 # number_episodes = 20000 # # # Initial", "1 --> Identity s: s + 1: [[0. 1. 0.", "env.close() plt.figure() plt.plot(rList, label=\"Return - Q Learning\") plt.show() plt.figure() plt.plot(jList,", "= 0 # Q network while j < 200: #", "tf.Variable(<initial-value>, name=<optional-name>) # tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) #", "table with new knowledge # Q[s, a] = Q[s, a]", "init = tf.global_variables_initializer() # Set learning parameters y = 0.99", "did with *0.01 W = tf.Variable(tf.random_uniform([env.observation_space.n, env.action_space.n], 0, 0.01)) #", "0. 0. 0. 0. 0. 0. 0. 0.]] # s", "[s:s+1] is a one-hot vector # Therefore W is the", "Learning\") plt.show() plt.figure() plt.plot(jList, label=\"Steps - Q Learning\") plt.show() #", "W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll += r s =", "j += 1 # # Choose an action by greedily", "is epsilon-greedy with epsilon decreasing over time # a =", "W) # Greedy action at a state predict = tf.argmax(Qout,", "Q[s, a] + lr * (r + y * np.max(Q[s1,", "= [] rList = [] with tf.Session() as sess: sess.run(init)", "the noise, it is epsilon-greedy with epsilon decreasing over time", "learning parameters y = 0.99 e = 0.1 number_episodes =", "# NEURAL NETWORK IMPLEMENTATION tf.reset_default_graph() # Feature vector for current", "a] with every a available at a state Qout =", "1))) # s1, r, d, _ = env.step(a) # #", "Feature vector for next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n],", "0.8 # y = 0.95 # number_episodes = 20000 #", "tensorflow as tf import numpy as np import matplotlib.pyplot as", "if np.random.rand(1) < e: a[0] = env.action_space.sample() s1, r, d,", "- Action state value for Q[s, a] with every a", "per episode jList = [] rList = [] with tf.Session()", "https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0 import gym import tensorflow as tf import numpy as", "s + 1: [[1. 0. 0. 0. 0. 0. 0.", "= tf.reduce_sum(tf.square(Qout - nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss)", "* np.max(Q[s1, :]) - Q[s, a]) # rAll += r", "- nextQ)) trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1) updateModel = trainer.minimize(loss) # TRAIN", "W1 = sess.run([updateModel, W], feed_dict={input1: np.identity(env.observation_space.n)[s:s+1], nextQ: targetQ}) rAll +=", "next state representation nextQ = tf.placeholder(shape=[1, env.action_space.n], dtype=tf.float32) # Entropy", "(number_episodes): # print(\"Episode #{} is running!\".format(i)) # s = env.reset()", "Q table with new knowledge # Q[s, a] = Q[s,", "action at a state predict = tf.argmax(Qout, axis=1) # Feature", "= allQ targetQ[0, a[0]] = r + y * maxQ1", "Qout with shape [1, env.action_space.n] - Action state value for", "tf import numpy as np import matplotlib.pyplot as plt env", "0. 0. 0. 0. 0. 0.]] # Identity [s:s+1] is", "# Update Q table with new knowledge # Q[s, a]", "env.action_space.n], 0, 0.01)) # Qout with shape [1, env.action_space.n] -", "d, _ = env.step(a) # # env.render() # # #" ]
[ "prf from tink import signature from tink import streaming_aead from", "tink import signature from tink import streaming_aead from tink.proto import", "2.0 (the \"License\"); # you may not use this file", "languages that are supported by a KeyType SUPPORTED_LANGUAGES = {", "# For each KeyType, a list of all KeyTemplate Names", "['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'],", "import hybrid from tink import mac from tink import prf", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG':", "'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey':", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for", "], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [", "by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] #", "['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4'", "'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM,", "'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey':", "SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template in KEY_TEMPLATE.items()", "'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go',", "signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, }", "'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc',", "from tink.proto import tink_pb2 # All languages supported by cross-language", "use this file except in compliance with the License. #", "streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256':", "'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519,", "from tink import daead from tink import hybrid from tink", "['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], }", "streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC,", "'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ]", "'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey':", "output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB':", "'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ],", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "[ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ],", "['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey':", "prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name:", "License. # You may obtain a copy of the License", "'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]]", "'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL", "signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512':", "'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go',", "tink import hybrid from tink import mac from tink import", "KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc',", "each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX,", "are supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc',", "{ 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES} #", "under the License is distributed on an \"AS IS\" BASIS,", "'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc',", "License for the specific language governing permissions and # limitations", "'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java',", "supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'],", "'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'],", "name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM,", "] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES", "signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363':", "for import for type annotations from tink import aead from", "( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES", "'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG,", "for type annotations from tink import aead from tink import", "prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for", "'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java',", "'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go',", "All languages supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java',", "[ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [", "'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4'", "['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java',", "'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java',", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG'", "'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4',", "['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc',", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'],", "'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256,", "'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES", "['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java',", "['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey':", "[ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey':", "], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [", "'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java',", "['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey':", ".ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG':", "language governing permissions and # limitations under the License. \"\"\"All", "'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go',", "'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key':", "'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363',", "= ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES +", "mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384':", "'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'],", "signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256':", "'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG':", "'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'],", "['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'],", "['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc',", "'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go',", "hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG,", "PRF_KEY_TYPES) # All languages that are supported by a KeyType", "= [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [", "'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'],", "KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in", "hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG,", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey',", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "that are supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey':", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "daead from tink import hybrid from tink import mac from", "'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [", "'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME", "to in writing, software # distributed under the License is", "'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'],", "# See the License for the specific language governing permissions", "'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ],", "+ 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB':", "or agreed to in writing, software # distributed under the", "'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc',", "'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384',", "required by applicable law or agreed to in writing, software", "signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF':", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey':", "['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ],", "'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = {", "SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java',", "[ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES =", "['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey':", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "# KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE =", "'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363,", "distributed under the License is distributed on an \"AS IS\"", "'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB,", "'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc',", "'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key':", "'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java',", "aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305':", "prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template", "{ 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'],", "mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384':", "'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java',", "SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are supported by", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "'java', 'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc',", "not use this file except in compliance with the License.", "['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as", "of all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES =", "writing, software # distributed under the License is distributed on", "governing permissions and # limitations under the License. \"\"\"All KeyTypes", "you may not use this file except in compliance with", "key_type: key_type for key_type in ALL_KEY_TYPES} # For each KeyType,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc',", "'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey':", "'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB,", "'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key',", "['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey':", "+ DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG':", "'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'],", "'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'],", "in ALL_KEY_TYPES} # For each KeyType, a list of all", "CONDITIONS OF ANY KIND, either express or implied. # See", "], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM',", "'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey':", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc',", "AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES +", "KeyType, a list of all KeyTemplate Names that must be", "+ HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All", "the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey',", "'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB',", "['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java',", "'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go',", "be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM',", "= [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES", "'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf)", "import prf from tink import signature from tink import streaming_aead", "'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate(", "'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc',", "annotations from tink import aead from tink import daead from", "[ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey',", "['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256',", "'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for each", "'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for each KeyTemplate", "OR CONDITIONS OF ANY KIND, either express or implied. #", "aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.'", "the License is distributed on an \"AS IS\" BASIS, #", "'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'],", "a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey':", "'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES", "'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [", "'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK),", "'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256',", "a list of all KeyTemplate Names that must be supported.", "mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363':", "'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'],", "'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'],", "'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate", "which languages support them.\"\"\" # Placeholder for import for type", "['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey':", "['cc', 'java', 'go', 'python'] # All KeyTypes (without the prefix", "], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363',", "import signature from tink import streaming_aead from tink.proto import tink_pb2", "(without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey',", "'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java',", "= ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES =", "tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB':", "law or agreed to in writing, software # distributed under", "['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java', 'go', 'python'], 'AesCtrHmacStreamingKey':", "and # limitations under the License. \"\"\"All KeyTypes and which", "'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc',", "aead from tink import daead from tink import hybrid from", "'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB,", "signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256':", "'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'],", "'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256,", "STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES", "tink import daead from tink import hybrid from tink import", "'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES =", "['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [", "['<KEY>'], } # KeyTemplate (as Protobuf) for each KeyTemplate name.", "] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES =", "['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey':", "may obtain a copy of the License at # #", "# All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [", "# Placeholder for import for type annotations from tink import", "+ PRF_KEY_TYPES) # All languages that are supported by a", "'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type:", "'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java',", "'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'],", "License. \"\"\"All KeyTypes and which languages support them.\"\"\" # Placeholder", "'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java',", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go',", "'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES", "All languages that are supported by a KeyType SUPPORTED_LANGUAGES =", "'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'],", "'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey':", "may not use this file except in compliance with the", "'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey':", "'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey':", "'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256,", "'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG',", "], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ],", "signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4':", "= ['cc', 'java', 'go', 'python'] # All KeyTypes (without the", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES", "this file except in compliance with the License. # You", "'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey',", "'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4,", "} SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template in", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "key_type for key_type in ALL_KEY_TYPES} # For each KeyType, a", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "# limitations under the License. \"\"\"All KeyTypes and which languages", "+ SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are supported", "'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name,", "'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey':", "signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519':", "['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [", "= { name: SUPPORTED_LANGUAGES[KEY_TYPE_FROM_URL[template.type_url]] for name, template in KEY_TEMPLATE.items() }", "'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'], 'EcdsaPrivateKey': ['cc', 'java',", "aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256':", "'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC':", "'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key':", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'],", "['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [", "streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256, 'AES_CMAC': mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG,", "tink import mac from tink import prf from tink import", "'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256,", "'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'],", "import streaming_aead from tink.proto import tink_pb2 # All languages supported", "'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL =", "# All languages that are supported by a KeyType SUPPORTED_LANGUAGES", "mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521':", "'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363,", "tink import aead from tink import daead from tink import", "'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES} # For", "= ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES =", "KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM':", "[ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384',", "[ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ],", "All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey',", "['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "tink import prf from tink import signature from tink import", "'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512,", "type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB,", "['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey':", "for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX':", "MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey',", "tink_pb2 # All languages supported by cross-language tests. ALL_LANGUAGES =", "or implied. # See the License for the specific language", "For each KeyType, a list of all KeyTemplate Names that", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey':", "['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey']", "'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey':", "'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey':", "] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ]", "aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256':", "'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'],", "aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV':", "'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc', 'java', 'go', 'python'],", "'java', 'go', 'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go',", "SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES =", "['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' +", "them.\"\"\" # Placeholder for import for type annotations from tink", "'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey':", "(the \"License\"); # you may not use this file except", "'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ]", "'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME = {", "# you may not use this file except in compliance", "aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305':", "'AesGcmKey': ['cc', 'java', 'go', 'python'], 'AesGcmSivKey': ['cc', 'python'], 'AesCtrHmacAeadKey': ['cc',", "'go', 'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java',", "'HkdfPrfKey': ['cc', 'java', 'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.'", "tink.proto import tink_pb2 # All languages supported by cross-language tests.", "'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey',", "'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go',", "'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG',", "'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521,", "signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363':", "'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'],", "'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key':", "# # Unless required by applicable law or agreed to", "'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey': ['cc',", "{ 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV':", "['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB',", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc', 'java', 'go', 'python'],", "languages support them.\"\"\" # Placeholder for import for type annotations", "'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES +", "Version 2.0 (the \"License\"); # you may not use this", "[ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ], 'AesCmacKey': ['AES_CMAC'], 'HmacKey': [ 'HMAC_SHA256_128BITTAG', 'HMAC_SHA256_256BITTAG',", "HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages", "from tink import mac from tink import prf from tink", "'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4,", "HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES", "['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go', 'python'], 'EciesAeadHkdfPrivateKey':", "'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'],", "implied. # See the License for the specific language governing", "], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256',", "import daead from tink import hybrid from tink import mac", "PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = (", "under the Apache License, Version 2.0 (the \"License\"); # you", "Placeholder for import for type annotations from tink import aead", "'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey':", "must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey':", "aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'),", "'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey',", "by applicable law or agreed to in writing, software #", "+ STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES)", "'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey',", "languages supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go',", "by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java', 'python'],", "[ 'AesCmacPrfKey', 'HmacPrfKey', 'HkdfPrfKey', ] ALL_KEY_TYPES = ( AEAD_KEY_TYPES +", "= { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM,", "(as Protobuf) for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX':", "prf.prf_key_templates.AES_CMAC, 'HMAC_PRF_SHA256': prf.prf_key_templates.HMAC_SHA256, 'HMAC_PRF_SHA512': prf.prf_key_templates.HMAC_SHA512, 'HKDF_PRF_SHA256': prf.prf_key_templates.HKDF_SHA256, } SUPPORTED_LANGUAGES_BY_TEMPLATE_NAME =", "AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ]", "MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that are", "[ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256' ],", "tink import streaming_aead from tink.proto import tink_pb2 # All languages", "'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' +", "= { 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go',", "'python'], 'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go',", "'java', 'go', 'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.')", "'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey': [ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4',", "Protobuf) for each KeyTemplate name. KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX,", "['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey': ['cc', 'java',", "'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4': signature.signature_key_templates.RSA_SSA_PSS_4096_SHA512_SHA512_64_F4, 'AES_CMAC_PRF': prf.prf_key_templates.AES_CMAC,", "} KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type", "= [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey', ] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES =", "'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey', 'RsaSsaPssPrivateKey', ] PRF_KEY_TYPES = [ 'AesCmacPrfKey', 'HmacPrfKey',", "'RsaSsaPkcs1PrivateKey': ['cc', 'java', 'python'], 'RsaSsaPssPrivateKey': ['cc', 'java', 'python'], 'AesCmacPrfKey': ['cc',", "import aead from tink import daead from tink import hybrid", "the License. \"\"\"All KeyTypes and which languages support them.\"\"\" #", "= [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES", "[ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey', 'RsaSsaPkcs1PrivateKey',", "'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'], 'RsaSsaPkcs1PrivateKey': ['cc',", "tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All KeyTypes", "from tink import aead from tink import daead from tink", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363',", "] ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES +", "signature from tink import streaming_aead from tink.proto import tink_pb2 #", "Unless required by applicable law or agreed to in writing,", "signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363':", "signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4':", "'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [", "'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384, 'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384,", "aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV':", "'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey']", "'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'],", "'go', 'python'], } KEY_TYPE_FROM_URL = { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type", "'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV,", "the specific language governing permissions and # limitations under the", "mac.mac_key_templates.AES_CMAC, 'HMAC_SHA256_128BITTAG': mac.mac_key_templates.HMAC_SHA256_128BITTAG, 'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256':", "'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'],", "applicable law or agreed to in writing, software # distributed", "limitations under the License. \"\"\"All KeyTypes and which languages support", "'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB',", "'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4,", "streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates .ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256,", "from tink import signature from tink import streaming_aead from tink.proto", "'HMAC_SHA256_256BITTAG', 'HMAC_SHA512_256BITTAG', 'HMAC_SHA512_512BITTAG' ], 'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521',", "signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4':", "in writing, software # distributed under the License is distributed", "aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB':", "each KeyType, a list of all KeyTemplate Names that must", "KeyTypes and which languages support them.\"\"\" # Placeholder for import", "'AES256_CTR_HMAC_SHA256'], 'ChaCha20Poly1305Key': ['CHACHA20_POLY1305'], 'XChaCha20Poly1305Key': ['XCHACHA20_POLY1305'], 'AesSivKey': ['AES256_SIV'], 'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB',", "+ MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) # All languages that", "cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All", "KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey':", "prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key',", "# All languages supported by cross-language tests. ALL_LANGUAGES = ['cc',", "list of all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES", "'HMAC_SHA256_256BITTAG': mac.mac_key_templates.HMAC_SHA256_256BITTAG, 'HMAC_SHA512_256BITTAG': mac.mac_key_templates.HMAC_SHA512_256BITTAG, 'HMAC_SHA512_512BITTAG': mac.mac_key_templates.HMAC_SHA512_512BITTAG, 'ECDSA_P256': signature.signature_key_templates.ECDSA_P256, 'ECDSA_P384': signature.signature_key_templates.ECDSA_P384,", "Names that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey': ['AES128_EAX',", "import mac from tink import prf from tink import signature", "permissions and # limitations under the License. \"\"\"All KeyTypes and", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "streaming_aead from tink.proto import tink_pb2 # All languages supported by", "'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], }", "daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB':", "ALL_KEY_TYPES = ( AEAD_KEY_TYPES + DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES", "+ key_type: key_type for key_type in ALL_KEY_TYPES} # For each", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "= { 'AesEaxKey': ['AES128_EAX', 'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV',", "signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4, 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4': signature.signature_key_templates.RSA_SSA_PSS_3072_SHA256_SHA256_32_F4, 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4':", "STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES + PRF_KEY_TYPES) #", "'AES256_EAX'], 'AesGcmKey': ['AES128_GCM', 'AES256_GCM'], 'AesGcmSivKey': ['AES128_GCM_SIV', 'AES256_GCM_SIV'], 'AesCtrHmacAeadKey': ['AES128_CTR_HMAC_SHA256', 'AES256_CTR_HMAC_SHA256'],", "'python'], 'ChaCha20Poly1305Key': ['java', 'go'], 'XChaCha20Poly1305Key': ['cc', 'java', 'go', 'python'], 'AesSivKey':", "'java', 'python'], 'AesCmacPrfKey': ['cc', 'java', 'go', 'python'], 'HmacPrfKey': ['cc', 'java',", "from tink import streaming_aead from tink.proto import tink_pb2 # All", "'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES = [ 'AesCtrHmacStreamingKey', 'AesGcmHkdfStreamingKey',", "'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363, 'ECDSA_P521_IEEE_P1363': signature.signature_key_templates.ECDSA_P521_IEEE_P1363, 'ED25519': signature.signature_key_templates.ED25519, 'RSA_SSA_PKCS1_3072_SHA256_F4': signature.signature_key_templates.RSA_SSA_PKCS1_3072_SHA256_F4, 'RSA_SSA_PKCS1_4096_SHA512_F4': signature.signature_key_templates.RSA_SSA_PKCS1_4096_SHA512_F4,", "'AesCtrHmacStreamingKey': [ 'AES128_CTR_HMAC_SHA256_4KB', 'AES256_CTR_HMAC_SHA256_4KB', ], 'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB',", "['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } # KeyTemplate (as Protobuf) for", "], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey': ['<KEY>'], } #", "= { 'type.googleapis.com/google.crypto.tink.' + key_type: key_type for key_type in ALL_KEY_TYPES}", "import for type annotations from tink import aead from tink", "the License for the specific language governing permissions and #", "under the License. \"\"\"All KeyTypes and which languages support them.\"\"\"", "type annotations from tink import aead from tink import daead", "] HYBRID_PRIVATE_KEY_TYPES = ['EciesAeadHkdfPrivateKey'] MAC_KEY_TYPES = [ 'AesCmacKey', 'HmacKey', ]", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE = {", "DAEAD_KEY_TYPES + STREAMING_AEAD_KEY_TYPES + HYBRID_PRIVATE_KEY_TYPES + MAC_KEY_TYPES + SIGNATURE_KEY_TYPES +", "'ECDSA_P384_SHA384': signature.signature_key_templates.ECDSA_P384_SHA384, 'ECDSA_P521': signature.signature_key_templates.ECDSA_P521, 'ECDSA_P256_IEEE_P1363': signature.signature_key_templates.ECDSA_P256_IEEE_P1363, 'ECDSA_P384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_IEEE_P1363, 'ECDSA_P384_SHA384_IEEE_P1363': signature.signature_key_templates.ECDSA_P384_SHA384_IEEE_P1363,", "[ 'RSA_SSA_PSS_3072_SHA256_SHA256_32_F4', 'RSA_SSA_PSS_4096_SHA512_SHA512_64_F4' ], 'AesCmacPrfKey': ['AES_CMAC_PRF'], 'HmacPrfKey': ['HMAC_PRF_SHA256', 'HMAC_PRF_SHA512'], 'HkdfPrfKey':", "= [ 'AesCmacKey', 'HmacKey', ] SIGNATURE_KEY_TYPES = [ 'EcdsaPrivateKey', 'Ed25519PrivateKey',", "mac from tink import prf from tink import signature from", "'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM': hybrid.hybrid_key_templates.ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256': hybrid.hybrid_key_templates", "from tink import hybrid from tink import mac from tink", "hybrid from tink import mac from tink import prf from", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV, 'AES256_GCM_SIV': aead.aead_key_templates.AES256_GCM_SIV, 'AES128_CTR_HMAC_SHA256': aead.aead_key_templates.AES128_CTR_HMAC_SHA256, 'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256,", "'go', 'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES", "'python'] # All KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES =", "'AesGcmHkdfStreamingKey': [ 'AES128_GCM_HKDF_4KB', 'AES256_GCM_HKDF_4KB', 'AES256_GCM_HKDF_1MB', ], 'EciesAeadHkdfPrivateKey': [ 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM', 'ECIES_P256_HKDF_HMAC_SHA256_AES128_CTR_HMAC_SHA256'", "'AesGcmKey', 'AesGcmSivKey', 'AesCtrHmacAeadKey', 'ChaCha20Poly1305Key', 'XChaCha20Poly1305Key', ] DAEAD_KEY_TYPES = ['AesSivKey'] STREAMING_AEAD_KEY_TYPES", "'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go', 'python'], 'HmacKey': ['cc',", "ALL_LANGUAGES = ['cc', 'java', 'go', 'python'] # All KeyTypes (without", "} # KeyTemplate (as Protobuf) for each KeyTemplate name. KEY_TEMPLATE", "'python'], 'EciesAeadHkdfPrivateKey': ['cc', 'java', 'go', 'python'], 'AesCmacKey': ['cc', 'java', 'go',", "all KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES = {", "key_type in ALL_KEY_TYPES} # For each KeyType, a list of", "KEY_TEMPLATE = { 'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM':", "\"License\"); # you may not use this file except in", "KeyTemplate Names that must be supported. KEY_TEMPLATE_NAMES = { 'AesEaxKey':", "'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "{ 'AesEaxKey': ['cc', 'java', 'python'], 'AesGcmKey': ['cc', 'java', 'go', 'python'],", "from tink import prf from tink import signature from tink", "streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB, 'AES128_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES128_GCM_HKDF_4KB, 'AES256_GCM_HKDF_4KB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_4KB, 'AES256_GCM_HKDF_1MB': streaming_aead.streaming_aead_key_templates.AES256_GCM_HKDF_1MB, 'ECIES_P256_HKDF_HMAC_SHA256_AES128_GCM':", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", "KeyTypes (without the prefix 'type.googleapis.com/google.crypto.tink.') AEAD_KEY_TYPES = [ 'AesEaxKey', 'AesGcmKey',", "import tink_pb2 # All languages supported by cross-language tests. ALL_LANGUAGES", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "and which languages support them.\"\"\" # Placeholder for import for", "ALL_KEY_TYPES} # For each KeyType, a list of all KeyTemplate", "'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305, 'AES256_SIV': daead.deterministic_aead_key_templates.AES256_SIV, 'AES128_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES128_CTR_HMAC_SHA256_4KB, 'AES256_CTR_HMAC_SHA256_4KB': streaming_aead.streaming_aead_key_templates.AES256_CTR_HMAC_SHA256_4KB,", "You may obtain a copy of the License at #", "support them.\"\"\" # Placeholder for import for type annotations from", "'AES256_CTR_HMAC_SHA256': aead.aead_key_templates.AES256_CTR_HMAC_SHA256, 'CHACHA20_POLY1305': tink_pb2.KeyTemplate( type_url=('type.googleapis.com/google.crypto.tink.' + 'ChaCha20Poly1305Key'), output_prefix_type=tink_pb2.TINK), 'XCHACHA20_POLY1305': aead.aead_key_templates.XCHACHA20_POLY1305,", "'python'], 'AesCtrHmacStreamingKey': ['cc', 'java', 'go', 'python'], 'AesGcmHkdfStreamingKey': ['cc', 'java', 'go',", "'python'], 'HmacPrfKey': ['cc', 'java', 'go', 'python'], 'HkdfPrfKey': ['cc', 'java', 'go',", "supported by cross-language tests. ALL_LANGUAGES = ['cc', 'java', 'go', 'python']", "the Apache License, Version 2.0 (the \"License\"); # you may", "supported by a KeyType SUPPORTED_LANGUAGES = { 'AesEaxKey': ['cc', 'java',", "'EcdsaPrivateKey': ['cc', 'java', 'go', 'python'], 'Ed25519PrivateKey': ['cc', 'java', 'go', 'python'],", "'ECDSA_P521_IEEE_P1363' ], 'Ed25519PrivateKey': ['ED25519'], 'RsaSsaPkcs1PrivateKey': [ 'RSA_SSA_PKCS1_3072_SHA256_F4', 'RSA_SSA_PKCS1_4096_SHA512_F4' ], 'RsaSsaPssPrivateKey':", "for key_type in ALL_KEY_TYPES} # For each KeyType, a list", "\"\"\"All KeyTypes and which languages support them.\"\"\" # Placeholder for", "'EcdsaPrivateKey': [ 'ECDSA_P256', 'ECDSA_P384', 'ECDSA_P384_SHA384', 'ECDSA_P521', 'ECDSA_P256_IEEE_P1363', 'ECDSA_P384_IEEE_P1363', 'ECDSA_P384_SHA384_IEEE_P1363', 'ECDSA_P521_IEEE_P1363'", "'AES128_EAX': aead.aead_key_templates.AES128_EAX, 'AES256_EAX': aead.aead_key_templates.AES256_EAX, 'AES128_GCM': aead.aead_key_templates.AES128_GCM, 'AES256_GCM': aead.aead_key_templates.AES256_GCM, 'AES128_GCM_SIV': aead.aead_key_templates.AES128_GCM_SIV," ]
[ "os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app", "@app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data =", "except Exception as e: data = {'error': str(e)} logging.error('Exception thrown", "response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response", "None try: data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found", "rs = RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) })", "RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is", "jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {} for key", "status=200, mimetype='application/json' ) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=True)", "'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>':", "return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200,", "import Flask, request, Response, json, jsonify from src.remote_signer import RemoteSigner", "mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET'])", "config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def", ") logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def", "format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample config used", "'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9", "logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as", "request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning", "key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response", "open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json", "under the MIT license ######################################################### from flask import Flask, request,", "indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try: data", "'public_key': key['public_key'] }) logging.info('Found public key {} for key hash", "= request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {} in", "else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not found',", "response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000,", "= { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732',", "logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not found', status=404)", "sample config used for testing config = { 'hsm_username': 'resigner',", "= json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash):", "Written by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC", "key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign", "= myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config =", "keys.json') with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '')", "data = {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response", "None try: if key_hash in config['keys']: key = config['keys'][key_hash] response", "JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST'])", "logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data) response =", "} } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json',", "'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key", "{}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None try:", "response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response", "keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile:", "'/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle':", "response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json'", "<NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC # released", "path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__)", "LLC # released under the MIT license ######################################################### from flask", "RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s',", "'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': {", "request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash))", "{}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash))", "key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key =", "config used for testing config = { 'hsm_username': 'resigner', 'hsm_slot':", "def sign(key_hash): response = None try: data = request.get_json(force=True) if", "config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] })", "if key_hash in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key", "used for testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1,", "{ '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 }", "(c) 2018 Blockscale LLC # released under the MIT license", "if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob", "{ 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys':", "for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for", "response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try: if", "{}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None", "'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7,", "'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening", "= None try: data = request.get_json(force=True) if key_hash in config['keys']:", "by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale LLC #", "'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': {", "in config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key']", "app = Flask(__name__) # sample config used for testing config", "= jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't", "Exception as e: data = {'error': str(e)} logging.error('Exception thrown during", "from flask import Flask, request, Response, json, jsonify from src.remote_signer", "logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys():", "return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ == '__main__':", "as e: data = {'error': str(e)} logging.error('Exception thrown during request:", "= {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response =", "{}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}),", "status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys',", "{}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle'])", "'<KEY>', 'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening keys.json')", "key = config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found", "public key for key hash {}\".format(key_hash)) response = Response('Key not", "flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return", "level=logging.INFO) app = Flask(__name__) # sample config used for testing", "@app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' )", "= Flask(__name__) # sample config used for testing config =", "}) logging.info('Found public key {} for key hash {}'.format(key['public_key'], key_hash))", "config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr':", "Flask(__name__) # sample config used for testing config = {", "public key {} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't", "'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>',", "key {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception", "myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob)", "# sample config used for testing config = { 'hsm_username':", "try: data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash", "import RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s", "} logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r')", "license ######################################################### from flask import Flask, request, Response, json, jsonify", "response = Response('Key not found', status=404) except Exception as e:", "key_hash in config['keys']: key = config['keys'][key_hash] response = jsonify({ 'public_key':", "get_public_key(key_hash): response = None try: if key_hash in config['keys']: key", "= jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {} for", "data = request.get_json(force=True) if key_hash in config['keys']: logging.info('Found key_hash {}", "logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response =", "logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response =", "as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>',", "1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so', 'node_addr': 'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key':", "'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully", "from os import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO)", "not found', status=404) except Exception as e: data = {'error':", "key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config,", "Copyright (c) 2018 Blockscale LLC # released under the MIT", ") logging.info('Returning flask response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def", "import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) #", "for key hash {}\".format(key_hash)) response = Response('Key not found', status=404)", "rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash))", "# Copyright (c) 2018 Blockscale LLC # released under the", "json, jsonify from src.remote_signer import RemoteSigner from os import path", "with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed", "'http://node.internal:8732', 'keys': { '<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle':", "json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON') config", "response = None try: data = request.get_json(force=True) if key_hash in", "Blockscale LLC # released under the MIT license ######################################################### from", "= RemoteSigner(config, data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response", "response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else:", "src.remote_signer import RemoteSigner from os import path import logging logging.basicConfig(filename='./remote-signer.log',", "# released under the MIT license ######################################################### from flask import", "methods=['GET']) def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if", "mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET'])", "methods=['GET']) def get_public_key(key_hash): response = None try: if key_hash in", "logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response = Response('Key", "response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response =", "contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response = None", "}) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response", "str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data),", "def get_public_key(key_hash): response = None try: if key_hash in config['keys']:", "= None try: if key_hash in config['keys']: key = config['keys'][key_hash]", "to sign {}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({", "'private_handle': 7, 'public_handle': 9 } } } logging.info('Opening keys.json') if", "= app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response))", "2018 Blockscale LLC # released under the MIT license #########################################################", "in config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash]", "authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ ==", "app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__ == '__main__': app.run(host='127.0.0.1',", "Response, json, jsonify from src.remote_signer import RemoteSigner from os import", "jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response)) else: logging.warning(\"Couldn't find", "key['public_key'] }) logging.info('Found public key {} for key hash {}'.format(key['public_key'],", "= config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public", "{}\".format(key_hash)) response = Response('Key not found', status=404) except Exception as", "logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config contains:", "9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json')", "released under the MIT license ######################################################### from flask import Flask,", "'<KEY>': { 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } }", "response {}'.format(response)) return response @app.route('/authorized_keys', methods=['GET']) def authorized_keys(): return app.response_class(", "try: if key_hash in config['keys']: key = config['keys'][key_hash] response =", "as myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as", "7, 'public_handle': 9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'):", "#!/usr/bin/env python3 ######################################################### # Written by <NAME>, <EMAIL> # Copyright", "{} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data))", "thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json'", "testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib': '/opt/cloudhsm/lib/libcloudhsm_pkcs11.so',", "methods=['POST']) def sign(key_hash): response = None try: data = request.get_json(force=True)", "app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return", "import path import logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app =", "from src.remote_signer import RemoteSigner from os import path import logging", "{} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key", "sign(key_hash): response = None try: data = request.get_json(force=True) if key_hash", "{}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key not", "logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash):", "python3 ######################################################### # Written by <NAME>, <EMAIL> # Copyright (c)", "response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key {}", "flask import Flask, request, Response, json, jsonify from src.remote_signer import", "%(message)s', level=logging.INFO) app = Flask(__name__) # sample config used for", "status=500, mimetype='application/json' ) logging.info('Returning flask response {}'.format(response)) return response @app.route('/keys/<key_hash>',", "logging.info('Found public key {} for key hash {}'.format(key['public_key'], key_hash)) else:", "key hash {}\".format(key_hash)) response = Response('Key not found', status=404) except", "# Written by <NAME>, <EMAIL> # Copyright (c) 2018 Blockscale", "is {}'.format(response)) else: logging.warning(\"Couldn't find key {}\".format(key_hash)) response = Response('Key", "hash {}\".format(key_hash)) response = Response('Key not found', status=404) except Exception", "= config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data)", "successfully as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2)))", "sign {}'.format(data)) rs = RemoteSigner(config, data) response = jsonify({ 'signature':", "key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key", "request, Response, json, jsonify from src.remote_signer import RemoteSigner from os", "'public_handle': 9 } } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found", "json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config, indent=2))) @app.route('/keys/<key_hash>', methods=['POST']) def sign(key_hash): response", "return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try:", "MIT license ######################################################### from flask import Flask, request, Response, json,", "######################################################### # Written by <NAME>, <EMAIL> # Copyright (c) 2018", "{'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class(", "logging logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample", "def authorized_keys(): return app.response_class( response=json.dumps({}), status=200, mimetype='application/json' ) if __name__", "the MIT license ######################################################### from flask import Flask, request, Response,", "in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs", "find key {}\".format(key_hash)) response = Response('Key not found', status=404) except", "key for key hash {}\".format(key_hash)) response = Response('Key not found',", "found', status=404) except Exception as e: data = {'error': str(e)}", "config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs = RemoteSigner(config, data) response", "'') logging.info('Parsed keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config", "during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' )", "} } } logging.info('Opening keys.json') if path.isfile('keys.json'): logging.info('Found keys.json') with", "{ 'public_key': '<KEY>', 'private_handle': 7, 'public_handle': 9 } } }", "{}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500, mimetype='application/json' ) logging.info('Returning flask", "jsonify from src.remote_signer import RemoteSigner from os import path import", "Flask, request, Response, json, jsonify from src.remote_signer import RemoteSigner from", "hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public key for key hash", "for testing config = { 'hsm_username': 'resigner', 'hsm_slot': 1, 'hsm_lib':", "logging.basicConfig(filename='./remote-signer.log', format='%(asctime)s %(message)s', level=logging.INFO) app = Flask(__name__) # sample config", "else: logging.warning(\"Couldn't public key for key hash {}\".format(key_hash)) response =", "######################################################### from flask import Flask, request, Response, json, jsonify from", "logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to", "keys.json successfully as JSON') config = json.loads(json_blob) logging.info('Config contains: {}'.format(json.dumps(config,", "= Response('Key not found', status=404) except Exception as e: data", "flask response {}'.format(response)) return response @app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response", "if key_hash in config['keys']: key = config['keys'][key_hash] response = jsonify({", "key {} for key hash {}'.format(key['public_key'], key_hash)) else: logging.warning(\"Couldn't public", "config['keys'][key_hash] response = jsonify({ 'public_key': key['public_key'] }) logging.info('Found public key", "data) response = jsonify({ 'signature': rs.sign(key['private_handle']) }) logging.info('Response is {}'.format(response))", "<EMAIL> # Copyright (c) 2018 Blockscale LLC # released under", "path.isfile('keys.json'): logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob =", "logging.error('Exception thrown during request: {}'.format(str(e))) response = app.response_class( response=json.dumps(data), status=500,", "myfile: json_blob = myfile.read().replace('\\n', '') logging.info('Parsed keys.json successfully as JSON')", "status=404) except Exception as e: data = {'error': str(e)} logging.error('Exception", "e: data = {'error': str(e)} logging.error('Exception thrown during request: {}'.format(str(e)))", "Response('Key not found', status=404) except Exception as e: data =", "@app.route('/keys/<key_hash>', methods=['GET']) def get_public_key(key_hash): response = None try: if key_hash", "config['keys']: logging.info('Found key_hash {} in config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting", "logging.info('Found keys.json') with open('keys.json', 'r') as myfile: json_blob = myfile.read().replace('\\n',", "config'.format(key_hash)) key = config['keys'][key_hash] logging.info('Attempting to sign {}'.format(data)) rs =", "response = None try: if key_hash in config['keys']: key =" ]
[ "unwind_info['Version'] == 1: unwind_codes = [ ] for i in", "in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating", "0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address):", "= ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER =", "('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view):", "+= view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names =", "RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress'] +=", "thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info -", "- Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if", "]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4)", "unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe =", "runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes',", "runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if", "import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III',", "if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0}", "range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address,", "return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo'))", "UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info,", "address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset',", "('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4),", "= RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None: runtime_function['BeginAddress']", "@ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end,", "'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address,", "= BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address):", "4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes", "funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end))", "UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER", "Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys,", "UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO", "read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is", "address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset'))", "address = UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code,", "binaryninja import log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage", "runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start", "read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO:", "('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address", "not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info,", "view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address", "= set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for", "Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view,", "+ unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set()", "unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4),", "view): base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3]", "unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end =", "address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not", "unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing", "split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ])", "unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0}", "runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not", "'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func in funcs:", "read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function", "= read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry'", "unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception", "unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs)))", "unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is not None:", "None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4)", "i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes']", "unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data", "1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code,", "from binaryninja import log from .utils import BinjaStruct, read_pe_header, split_bits,", "if runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not", "[ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version']", "'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER =", "4) ]) if unwind_info['Version'] == 1: unwind_codes = [ ]", "in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] =", "is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo',", "info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info", "not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] +=", "info_address) if unwind_info is None: continue if 'FunctionEntry' in unwind_info:", "'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if", "0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12):", "pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys +", "address def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view)", "5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4,", "start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue", "0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3", "4, 4) ]) if unwind_info['Version'] == 1: unwind_codes = [", "= pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys", "Info - Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address)", "address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view,", "12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind", ".utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t =", "is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData']", "('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] ==", "'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if", "is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if", "3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0,", "break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found", "= runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is", "continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled:", "unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address", "unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address)", "unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break", "def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code", "# https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData'))", "UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view,", "unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address", "BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function,", "runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None: continue", "'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return", "0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if", "for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code)", "unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None: continue", "range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes", "log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx", "for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread,", "read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end", "address = UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info,", "= read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names", "{0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is", "if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info", "runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t", "if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0,", "UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def", "= 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func in", "unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys,", "base_address = view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys", "runtime_function is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address):", "[ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset',", "{0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func in funcs: view.create_user_function(func)", "'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2", "('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1: unwind_codes =", "address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp',", "4), ('OpInfo', 4, 4) ]) return unwind_code, address def parse_unwind_info(thread,", "None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if", "is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags',", "('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view,", "= read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] &", "return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog',", "if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData']", "]) return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start", "return unwind_code, address def parse_unwind_info(thread, view): base_address = view.start pe", "0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address =", "continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if", "0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister',", "unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info,", "BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address", "continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ =", "read_unwind_info(view, info_address) if unwind_info is None: continue if 'FunctionEntry' in", "address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB',", "== 1: unwind_codes = [ ] for i in range(unwind_info['CountOfCodes']):", "https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def", "+ unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X} =>", "unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3),", "continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address):", "not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs)))", "def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if", "0, 4), ('FrameOffset', 4, 4) ]) if unwind_info['Version'] == 1:", "= read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address + unwind_directory.VirtualAddress", "None: continue if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not", "address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is not None:", "not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0, 4), ('OpInfo', 4,", "read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address = runtime_function['BeginAddress']", "if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view,", "address, 4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start", "0, 4), ('OpInfo', 4, 4) ]) return unwind_code, address def", "base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs =", "names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address", "UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [", "= unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view,", "continue funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs))", "not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3,", "= BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code,", "read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names =", "thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for func", "= ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view, address): runtime_function, address =", "= [ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address =", "import log from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage #", "runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address) if unwind_info is None:", "if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [ ('UnwindOp', 0,", "= 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view, address): unwind_info, address", "runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return", "view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _", "view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function, address", "= 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4 def read_unwind_info(view,", "unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def", "= 0x4 def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address)", "unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address)", "BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0", "address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags']", "runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address =", "def parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory", "def read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info", "4) if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress']", "unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address =", "if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return", "'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _ =", "address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version',", "('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [", "= unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @", "0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled:", "unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not None:", "] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view, address)", "= BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER =", "+= view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t =", "('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1", "UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t", "4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address =", "pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys = base_address +", "= view.start pe = read_pe_header(view) unwind_directory = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] unwind_entrys =", "functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function is None:", "split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress',", "runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys,", "unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t =", "address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4) if runtime_function is", "BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names", "0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO = 0x4", "= base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size funcs", "= 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER = 0x3 UNW_FLAG_CHAININFO =", "in range(unwind_entrys, unwind_entrys_end, 12): if thread.cancelled: break update_percentage(thread, unwind_entrys, unwind_entrys_end,", "update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress',", "Found {0} functions'.format(len(funcs))) runtime_function, _ = read_runtime_function(view, runtime_address) if runtime_function", "'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress =", "None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start", "view.start runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB',", "'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ]) split_bits(unwind_info,", "= ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view,", "= UNWIND_INFO_t.read(view, address) if unwind_info is not None: split_bits(unwind_info, 'VersionAndFlags',", "thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found {0} functions'.format(len(funcs))) for", "3, 5) ]) split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset',", "runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function, _", "4, 4) ]) return unwind_code, address def parse_unwind_info(thread, view): base_address", "RUNTIME_FUNCTION_t = BinjaStruct('<III', names = ('BeginAddress', 'EndAddress', 'UnwindData')) def read_runtime_function(view,", "+= view.start runtime_function['EndAddress'] += view.start runtime_function['UnwindData'] += view.start return runtime_function,", "read_unwind_info(view, address): unwind_info, address = UNWIND_INFO_t.read(view, address) if unwind_info is", "unwind_code, address = read_unwind_code(view, address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if", "if 'FunctionEntry' in unwind_info: continue funcs.add(start_address) if not thread.cancelled: thread.progress", "[ ] for i in range(unwind_info['CountOfCodes']): unwind_code, address = read_unwind_code(view,", "UNWIND_CODE_t = BinjaStruct('<BB', names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address):", "('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address = UNWIND_CODE_t.read(view, address)", "is None: continue start_address = runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue", "unwind_entrys + unwind_directory.Size funcs = set() log.log_info('Exception Data @ 0x{0:X}", "= read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address =", "= runtime_function['BeginAddress'] if not view.is_offset_executable(start_address): continue if view.get_functions_containing(start_address): continue info_address", "_ = read_unwind_info(view, info_address) if unwind_info is None: continue if", "'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER", "]) if unwind_info['Version'] == 1: unwind_codes = [ ] for", "if unwind_info is None: continue if 'FunctionEntry' in unwind_info: continue", "[ ('UnwindOp', 0, 4), ('OpInfo', 4, 4) ]) return unwind_code,", "update_percentage(thread, unwind_entrys, unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0}", "_ = read_runtime_function(view, runtime_address) if runtime_function is None: continue start_address", "None: split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5)", "split_bits(unwind_info, 'FrameRegisterAndOffset', [ ('FrameRegister', 0, 4), ('FrameOffset', 4, 4) ])", "log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in", "unwind_entrys_end, runtime_address, 'Parsing Unwind Info - Found {0} functions'.format(len(funcs))) runtime_function,", "split_bits(unwind_info, 'VersionAndFlags', [ ('Version', 0, 3), ('Flags', 3, 5) ])", "set() log.log_info('Exception Data @ 0x{0:X} => 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address", "& UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'], address = read_runtime_function(view, address) return unwind_info, address", "if unwind_info['Version'] == 1: unwind_codes = [ ] for i", "from .utils import BinjaStruct, read_pe_header, split_bits, update_percentage # https://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx RUNTIME_FUNCTION_t", "= UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo',", "runtime_function['UnwindData'] += view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names", "view.get_functions_containing(start_address): continue info_address = runtime_function['UnwindData'] unwind_info, _ = read_unwind_info(view, info_address)", "UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER", "address): unwind_code, address = UNWIND_CODE_t.read(view, address) if unwind_code is not", "if runtime_function is not None: runtime_function['BeginAddress'] += view.start runtime_function['EndAddress'] +=", "= 0x0 UNW_FLAG_EHANDLER = 0x1 UNW_FLAG_UHANDLER = 0x2 UNW_FLAG_FHANDLER =", "address) unwind_codes.append(unwind_code) unwind_info['UnwindCodes'] = unwind_codes if unwind_info['Flags'] & UNW_FLAG_CHAININFO: unwind_info['FunctionEntry'],", "read_runtime_function(view, address) return unwind_info, address UNWIND_CODE_t = BinjaStruct('<BB', names =", "names = ('CodeOffset', 'UnwindOpAndInfo')) def read_unwind_code(view, address): unwind_code, address =", "'UnwindData')) def read_runtime_function(view, address): runtime_function, address = RUNTIME_FUNCTION_t.read(view, address, 4)", "UNWIND_CODE_t.read(view, address) if unwind_code is not None: split_bits(unwind_code, 'UnwindOpAndInfo', [", "parse_unwind_info(thread, view): base_address = view.start pe = read_pe_header(view) unwind_directory =", "=> 0x{1:X}'.format(unwind_entrys, unwind_entrys_end)) for runtime_address in range(unwind_entrys, unwind_entrys_end, 12): if", "funcs.add(start_address) if not thread.cancelled: thread.progress = 'Creating {0} Function'.format(len(funcs)) log.log_info('Found", "unwind_entrys = base_address + unwind_directory.VirtualAddress unwind_entrys_end = unwind_entrys + unwind_directory.Size", "names = ('VersionAndFlags', 'SizeOfProlog', 'CountOfCodes', 'FrameRegisterAndOffset')) UNW_FLAG_NHANDLER = 0x0 UNW_FLAG_EHANDLER", "view.start return runtime_function, address UNWIND_INFO_t = BinjaStruct('<BBBB', names = ('VersionAndFlags'," ]
[ "3) Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects", "render the figure. \"\"\" import plotly.graph_objects as go import numpy", "as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a", "powerful library like Open3D. Plotly however supports animations, buttons and", "with `fig = init_figure()` 2) Plot points, cameras, lines, or", "noqa E741 return fig def plot_points(fig, pts, color='rgba(255, 0, 0,", "w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W,", "np.array([[0, 0], [W, 0], [W, H], [0, H], [0, 0]])", "[0, H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners", "go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False)", "t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a", "camera frustum.\"\"\" x, y, z = t u, v, w", "traces (e.g. 3D points).\"\"\" slider = {'steps': []} frames =", "however supports animations, buttons and sliders. 1) Initialize a figure", "Call `fig.show()` to render the figure. \"\"\" import plotly.graph_objects as", "2]*2 corners = np.array([[0, 0], [W, 0], [W, H], [0,", "0], [W, H], [0, H], [0, 0]]) corners = to_homogeneous(corners)", "2) Plot points, cameras, lines, or create a slider animation.", "a slider that animates a list of traces (e.g. 3D", "{\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames", "with camera frustum.\"\"\" x, y, z = t u, v,", "tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [", "x, y, z = corners.T tr = go.Scatter3d( x=x, y=y,", "H], [0, H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T", "to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure()", "corners = (corners/2) @ R.T + t x, y, z", "[W, 0], [W, H], [0, H], [0, 0]]) corners =", "tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'),", "3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1,", "points.\"\"\" x, y, z = pts.T tr = go.Scatter3d( x=x,", "z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0,", "0, 1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\" x,", "marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0,", "R @ -np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y],", "= to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T +", "z = t u, v, w = R @ -np.array([0,", "`fig.show()` to render the figure. \"\"\" import plotly.graph_objects as go", "points).\"\"\" slider = {'steps': []} frames = [] fig.add_trace(traces[0]) idx", "0, 255)'): \"\"\"Plot a camera as a cone with camera", "[] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr", "create a slider animation. 3) Call `fig.show()` to render the", "-np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u],", "corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0,", "z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]],", "yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa", "= np.array([[0, 0], [W, 0], [W, H], [0, H], [0,", "len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx],", "\"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames)", "marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'):", "primitives based on Plotly. We might want to instead use", "= {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\":", "list of traces (e.g. 3D points).\"\"\" slider = {'steps': []}", "figure with `fig = init_figure()` 2) Plot points, cameras, lines,", "a list of traces (e.g. 3D points).\"\"\" slider = {'steps':", "init_figure()` 2) Plot points, cameras, lines, or create a slider", "scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0))", "= [] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i,", "fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2 corners =", "3D visualization primitives based on Plotly. We might want to", "1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w],", "tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip',", "K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a cone", "y, z = corners.T tr = go.Scatter3d( x=x, y=y, z=z,", "u, v, w = R @ -np.array([0, 0, 1]) tr", "fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict(", "to render the figure. \"\"\" import plotly.graph_objects as go import", "a more powerful library like Open3D. Plotly however supports animations,", "import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig =", "x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr)", "animates a list of traces (e.g. 3D points).\"\"\" slider =", "based on Plotly. We might want to instead use a", "z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t,", "t u, v, w = R @ -np.array([0, 0, 1])", "= go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1.,", "of traces (e.g. 3D points).\"\"\" slider = {'steps': []} frames", "i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames) fig.layout.sliders = (slider,)", "that animates a list of traces (e.g. 3D points).\"\"\" slider", "(e.g. 3D points).\"\"\" slider = {'steps': []} frames = []", "<filename>pixloc/visualization/viz_3d.py \"\"\" 3D visualization primitives based on Plotly. We might", "color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set of 3D", "E741 return fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)',", "(corners/2) @ R.T + t x, y, z = corners.T", "\"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames) fig.layout.sliders =", "x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig,", "255)'): \"\"\"Plot a camera as a cone with camera frustum.\"\"\"", "- 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr]))", "sliders. 1) Initialize a figure with `fig = init_figure()` 2)", "numpy as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize", "color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2,", "t=0, pad=0)) # noqa E741 return fig def plot_points(fig, pts,", "fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot", "go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def", "@ np.linalg.inv(K).T corners = (corners/2) @ R.T + t x,", "Initialize a figure with `fig = init_figure()` 2) Plot points,", "def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a", "want to instead use a more powerful library like Open3D.", "pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set of", "anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H", "frustum.\"\"\" x, y, z = t u, v, w =", "for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step =", "fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot", "showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H =", "Plotly however supports animations, buttons and sliders. 1) Initialize a", "= len(fig.data) - 1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i),", "R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera as", "1) Initialize a figure with `fig = init_figure()` 2) Plot", "go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)),", "supports animations, buttons and sliders. 1) Initialize a figure with", "margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741 return fig", "of 3D points.\"\"\" x, y, z = pts.T tr =", "fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0,", "corners = np.array([[0, 0], [W, 0], [W, H], [0, H],", "import plotly.graph_objects as go import numpy as np from ..pixlib.geometry.utils", "0, 0, 1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\"", "= K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W,", "x, y, z = pts.T tr = go.Scatter3d( x=x, y=y,", "= (corners/2) @ R.T + t x, y, z =", "use a more powerful library like Open3D. Plotly however supports", "y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R,", "np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D", "# noqa E741 return fig def plot_points(fig, pts, color='rgba(255, 0,", "[W, H], [0, H], [0, 0]]) corners = to_homogeneous(corners) @", "+ t x, y, z = corners.T tr = go.Scatter3d(", "frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\":", "visualization primitives based on Plotly. We might want to instead", "\"\"\" import plotly.graph_objects as go import numpy as np from", "\"\"\" 3D visualization primitives based on Plotly. We might want", "go import numpy as np from ..pixlib.geometry.utils import to_homogeneous def", "and sliders. 1) Initialize a figure with `fig = init_figure()`", "traces): \"\"\"Create a slider that animates a list of traces", "buttons and sliders. 1) Initialize a figure with `fig =", "the figure. \"\"\" import plotly.graph_objects as go import numpy as", "= init_figure()` 2) Plot points, cameras, lines, or create a", "v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr)", "points, cameras, lines, or create a slider animation. 3) Call", "y, z = t u, v, w = R @", "library like Open3D. Plotly however supports animations, buttons and sliders.", "create_slider_animation(fig, traces): \"\"\"Create a slider that animates a list of", "color='rgb(0, 0, 255)'): \"\"\"Plot a camera as a cone with", "def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout(", "set of 3D points.\"\"\" x, y, z = pts.T tr", "camera as a cone with camera frustum.\"\"\" x, y, z", "0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create", "`fig = init_figure()` 2) Plot points, cameras, lines, or create", "We might want to instead use a more powerful library", "= {'steps': []} frames = [] fig.add_trace(traces[0]) idx = len(fig.data)", "plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2): \"\"\"Plot a set", "fig.add_trace(traces[0]) idx = len(fig.data) - 1 for i, tr in", "figure. \"\"\" import plotly.graph_objects as go import numpy as np", "might want to instead use a more powerful library like", "z = corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0,", "0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a", "return fig def plot_points(fig, pts, color='rgba(255, 0, 0, 1)', ps=2):", "showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that animates", "y, z = pts.T tr = go.Scatter3d( x=x, y=y, z=z,", "slider that animates a list of traces (e.g. 3D points).\"\"\"", "init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height,", "pad=0)) # noqa E741 return fig def plot_points(fig, pts, color='rgba(255,", "H = K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0],", "to instead use a more powerful library like Open3D. Plotly", "t x, y, z = corners.T tr = go.Scatter3d( x=x,", "np.linalg.inv(K).T corners = (corners/2) @ R.T + t x, y,", "dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741 return", "color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2", "pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color,", "a set of 3D points.\"\"\" x, y, z = pts.T", "= go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr)", "u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1, color]], sizemode='absolute')", "up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0,", "a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0.,", "z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0,", "frames = [] fig.add_trace(traces[0]) idx = len(fig.data) - 1 for", "= go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False,", "sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1, 2]*2 corners", "cone with camera frustum.\"\"\" x, y, z = t u,", "as a cone with camera frustum.\"\"\" x, y, z =", "@ R.T + t x, y, z = corners.T tr", "corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T", "like Open3D. Plotly however supports animations, buttons and sliders. 1)", "colorscale=[[0, color], [1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0,", "[0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2)", "eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data',", "to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @ R.T + t", "= R @ -np.array([0, 0, 1]) tr = go.Cone( x=[x],", "height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False),", "0], [W, 0], [W, H], [0, H], [0, 0]]) corners", "{\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step)", "animations, buttons and sliders. 1) Initialize a figure with `fig", "x, y, z = t u, v, w = R", "[1, color]], sizemode='absolute') fig.add_trace(tr) W, H = K[0, 2]*2, K[1,", "1)', ps=2): \"\"\"Plot a set of 3D points.\"\"\" x, y,", "0, 1]) tr = go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v],", "line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces):", "3D points).\"\"\" slider = {'steps': []} frames = [] fig.add_trace(traces[0])", "in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)],", "traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True},", "True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames =", "slider animation. 3) Call `fig.show()` to render the figure. \"\"\"", "mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K,", "tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps, marker_color=color, marker_line_width=.2)", "a camera as a cone with camera frustum.\"\"\" x, y,", "step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}],", "as go import numpy as np from ..pixlib.geometry.utils import to_homogeneous", "\"\"\"Plot a camera as a cone with camera frustum.\"\"\" x,", "xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) #", "scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False),", "ps=2): \"\"\"Plot a set of 3D points.\"\"\" x, y, z", "figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2),", "\"\"\"Plot a set of 3D points.\"\"\" x, y, z =", "a slider animation. 3) Call `fig.show()` to render the figure.", "1 for i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step", "\"immediate\"}], \"label\": i, \"method\": \"animate\"} slider['steps'].append(step) fig.frames = tuple(frames) fig.layout.sliders", "def create_slider_animation(fig, traces): \"\"\"Create a slider that animates a list", "z = pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers',", "aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0, t=0, pad=0)) # noqa E741", "v, w = R @ -np.array([0, 0, 1]) tr =", "y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'),", "a cone with camera frustum.\"\"\" x, y, z = t", "i, tr in enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\":", "= go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001),", "on Plotly. We might want to instead use a more", "def plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a", ".5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider", "marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that", "fig.add_trace(tr) def create_slider_animation(fig, traces): \"\"\"Create a slider that animates a", "{'steps': []} frames = [] fig.add_trace(traces[0]) idx = len(fig.data) -", "plotly.graph_objects as go import numpy as np from ..pixlib.geometry.utils import", "w = R @ -np.array([0, 0, 1]) tr = go.Cone(", "{\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i,", "idx = len(fig.data) - 1 for i, tr in enumerate(traces):", "0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners = (corners/2) @", "y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showbackground=False), aspectmode='data', dragmode='orbit'), margin=dict(l=0, r=0, b=0,", "or create a slider animation. 3) Call `fig.show()` to render", "[ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\":", "x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color],", "= corners.T tr = go.Scatter3d( x=x, y=y, z=z, line=dict(color='rgba(0, 0,", "animation. 3) Call `fig.show()` to render the figure. \"\"\" import", "K[1, 2]*2 corners = np.array([[0, 0], [W, 0], [W, H],", "Plotly. We might want to instead use a more powerful", "= pts.T tr = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker_size=ps,", "@ -np.array([0, 0, 1]) tr = go.Cone( x=[x], y=[y], z=[z],", "3D points.\"\"\" x, y, z = pts.T tr = go.Scatter3d(", "W, H = K[0, 2]*2, K[1, 2]*2 corners = np.array([[0,", "y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0, color], [1,", "H], [0, 0]]) corners = to_homogeneous(corners) @ np.linalg.inv(K).T corners =", "import numpy as np from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800):", "Open3D. Plotly however supports animations, buttons and sliders. 1) Initialize", "r=0, b=0, t=0, pad=0)) # noqa E741 return fig def", "[]} frames = [] fig.add_trace(traces[0]) idx = len(fig.data) - 1", "a figure with `fig = init_figure()` 2) Plot points, cameras,", "plot_camera(fig, R, t, K, color='rgb(0, 0, 255)'): \"\"\"Plot a camera", "b=0, t=0, pad=0)) # noqa E741 return fig def plot_points(fig,", "enumerate(traces): frames.append(go.Frame(name=str(i), traces=[idx], data=[tr])) step = {\"args\": [ [str(i)], {\"frame\":", "[str(i)], {\"frame\": {\"redraw\": True}, \"mode\": \"immediate\"}], \"label\": i, \"method\": \"animate\"}", "..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\" fig", "K[0, 2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W, 0],", "data=[tr])) step = {\"args\": [ [str(i)], {\"frame\": {\"redraw\": True}, \"mode\":", "more powerful library like Open3D. Plotly however supports animations, buttons", "Plot points, cameras, lines, or create a slider animation. 3)", "instead use a more powerful library like Open3D. Plotly however", "\"\"\"Initialize a 3D figure.\"\"\" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict(", "= t u, v, w = R @ -np.array([0, 0,", "lines, or create a slider animation. 3) Call `fig.show()` to", "2]*2, K[1, 2]*2 corners = np.array([[0, 0], [W, 0], [W,", "y=y, z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def", "\"\"\"Create a slider that animates a list of traces (e.g.", "z=z, line=dict(color='rgba(0, 0, 0, .5)'), marker=dict(size=0.0001), showlegend=False) fig.add_trace(tr) def create_slider_animation(fig,", "slider = {'steps': []} frames = [] fig.add_trace(traces[0]) idx =", "marker_color=color, marker_line_width=.2) fig.add_trace(tr) def plot_camera(fig, R, t, K, color='rgb(0, 0,", "R.T + t x, y, z = corners.T tr =", "cameras, lines, or create a slider animation. 3) Call `fig.show()`", "from ..pixlib.geometry.utils import to_homogeneous def init_figure(height=800): \"\"\"Initialize a 3D figure.\"\"\"", "go.Cone( x=[x], y=[y], z=[z], u=[u], v=[v], w=[w], anchor='tip', showscale=False, colorscale=[[0," ]
[ "-> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray)", "np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] = True", "= [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i :", "list[list[int]]: return [[int(n) for n in line.split()] for line in", "i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False", "GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for _", "id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1)", "checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum() def", "victory, else set of id of the wining grids\"\"\" return", "[int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i", "def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no", "= 0 return grid.sum() def main() -> None: with open(\"input.txt\")", "print(\"part1:\", s * random_numbers[i]) q1_done = True if len(grids) ==", "True if len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0]", "len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] *", "read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n in line.split()]", "win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) ==", "def main() -> None: with open(\"input.txt\") as f: lines =", "sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i", "len(winning_set) == 1 and not q1_done: index = list(winning_set)[0] s", "f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")] grids =", "in range(len(grids))]) win = False i = 0 q1_done =", "check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if no victory,", "f: lines = f.readlines() random_numbers = [int(n) for n in", "wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] )", "random_numbers[i]) q1_done = True if len(grids) == len(winning_set) + 1:", "the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0]", "return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid:", "in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for", "range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in range(len(grids))]) win", "q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s", "_ in range(len(grids))]) win = False i = 0 q1_done", "range(len(grids))]) win = False i = 0 q1_done = False", "s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s)", "True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set if", "no victory, else set of id of the wining grids\"\"\"", "= np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in range(2,", "0 return grid.sum() def main() -> None: with open(\"input.txt\") as", "== len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i]", "* s) return i += 1 if __name__ == \"__main__\":", "for n in line.split()] for line in lines] def bingo_step(grids:", "grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def", "\"\"\"return empty set if no victory, else set of id", "lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None:", "random_numbers[i], s, random_numbers[i] * s) return i += 1 if", "as f: lines = f.readlines() random_numbers = [int(n) for n", "= f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")] grids", "_ in range(GRID_SIZE)] for _ in range(len(grids))]) win = False", "len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids)", "index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s *", "grid.sum() def main() -> None: with open(\"input.txt\") as f: lines", "int) -> None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids:", "q1_done = False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set", "len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for _ in", "if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i],", "= False i = 0 q1_done = False while not", "= False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set =", "in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in range(len(grids))])", "+ GRID_SIZE]) for i in range(2, len(lines), 1 + GRID_SIZE)])", "GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n)", "GRID_SIZE]) for i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids", "return grid.sum() def main() -> None: with open(\"input.txt\") as f:", "list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\",", "= 0 q1_done = False while not win: bingo_step(grids, checked_grids,", ": i + GRID_SIZE]) for i in range(2, len(lines), 1", "_ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _ in", "number: int) -> None: checked_grids[np.where(grids == number)] = True def", "of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union(", "np.ndarray) -> set[int]: \"\"\"return empty set if no victory, else", "-> set[int]: \"\"\"return empty set if no victory, else set", "-> int: grid[checked_grid] = 0 return grid.sum() def main() ->", "checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray) -> set[int]:", "lines = f.readlines() random_numbers = [int(n) for n in lines[0].split(\",\")]", "random_numbers = [int(n) for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i", "q1_done = True if len(grids) == len(winning_set) + 1: index_last_to_win", "s) return i += 1 if __name__ == \"__main__\": main()", "1 and not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index],", "for line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number:", "-> None: with open(\"input.txt\") as f: lines = f.readlines() random_numbers", "np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum() def main()", "print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i += 1", "5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray)", "= np.array([[[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]", "for _ in range(len(grids))]) win = False i = 0", "line.split()] for line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray,", "while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if", "5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid]", "of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) ==", "np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)]", "== len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) ==", "len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s,", "False while not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids)", "if len(grids) == len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if", "lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i", "not win: bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set)", "+ 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s", "= 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for", "s, random_numbers[i] * s) return i += 1 if __name__", "list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done", "for n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i +", "== 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid:", "== number)] = True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return", "sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True if", "0 q1_done = False while not win: bingo_step(grids, checked_grids, random_numbers[i])", "random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1 and not", "win = False i = 0 q1_done = False while", "main() -> None: with open(\"input.txt\") as f: lines = f.readlines()", "= sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True", "in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for", "for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for _", "== 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int:", "<filename>day04/c.py import numpy as np GRID_SIZE = 5 def read_bingo_grid(lines:", "np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return grid.sum()", "check_victory(checked_grids) if len(winning_set) == 1 and not q1_done: index =", "range(2, len(lines), 1 + GRID_SIZE)]) checked_grids = np.array([[[False for _", "[[int(n) for n in line.split()] for line in lines] def", "-> list[list[int]]: return [[int(n) for n in line.split()] for line", "None: checked_grids[np.where(grids == number)] = True def check_victory(check_grids: np.ndarray) ->", "= True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty set", "checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for _ in", "with open(\"input.txt\") as f: lines = f.readlines() random_numbers = [int(n)", "n in lines[0].split(\",\")] grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE])", "s * random_numbers[i]) q1_done = True if len(grids) == len(winning_set)", "= check_victory(checked_grids) if len(winning_set) == 1 and not q1_done: index", "5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n", "False i = 0 q1_done = False while not win:", "in line.split()] for line in lines] def bingo_step(grids: np.ndarray, checked_grids:", "empty set if no victory, else set of id of", "np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) ->", "grids = np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in", "if no victory, else set of id of the wining", "None: with open(\"input.txt\") as f: lines = f.readlines() random_numbers =", "return [[int(n) for n in line.split()] for line in lines]", "= sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return", "sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0 return", "int: grid[checked_grid] = 0 return grid.sum() def main() -> None:", "set if no victory, else set of id of the", "bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids ==", "random_numbers[i] * s) return i += 1 if __name__ ==", "checked_grids[index_last_to_win]) print(\"part2:\", random_numbers[i], s, random_numbers[i] * s) return i +=", "1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s =", "* random_numbers[i]) q1_done = True if len(grids) == len(winning_set) +", "import numpy as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str])", "for _ in range(GRID_SIZE)] for _ in range(len(grids))]) win =", "else set of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1)", "i = 0 q1_done = False while not win: bingo_step(grids,", "= list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i])", "line in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int)", "for i in range(2, len(lines), 1 + GRID_SIZE)]) checked_grids =", "numpy as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) ->", "len(winning_set) + 1: index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set):", "set[int]: \"\"\"return empty set if no victory, else set of", "and not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index])", "s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done =", "as np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]:", "set(np.where(check_grids.sum(axis=1).max(axis=1) == 5)[0]).union( np.where(check_grids.sum(axis=2).max(axis=1) == 5)[0] ) def sum_grid(grid: np.ndarray,", ") def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] =", "open(\"input.txt\") as f: lines = f.readlines() random_numbers = [int(n) for", "number)] = True def check_victory(check_grids: np.ndarray) -> set[int]: \"\"\"return empty", "checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1 and", "= True if len(grids) == len(winning_set) + 1: index_last_to_win =", "n in line.split()] for line in lines] def bingo_step(grids: np.ndarray,", "1 + GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)]", "checked_grids[index]) print(\"part1:\", s * random_numbers[i]) q1_done = True if len(grids)", "list[str]) -> list[list[int]]: return [[int(n) for n in line.split()] for", "index_last_to_win = list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win],", "def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids", "winning_set = check_victory(checked_grids) if len(winning_set) == 1 and not q1_done:", "= list(set(range(len(grids))).difference(winning_set))[0] if len(grids) == len(winning_set): s = sum_grid(grids[index_last_to_win], checked_grids[index_last_to_win])", "in range(GRID_SIZE)] for _ in range(len(grids))]) win = False i", "np.array([read_bingo_grid(lines[i : i + GRID_SIZE]) for i in range(2, len(lines),", "np.array([[[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)] for", "i + GRID_SIZE]) for i in range(2, len(lines), 1 +", "+ GRID_SIZE)]) checked_grids = np.array([[[False for _ in range(GRID_SIZE)] for", "if len(winning_set) == 1 and not q1_done: index = list(winning_set)[0]", "in lines] def bingo_step(grids: np.ndarray, checked_grids: np.ndarray, number: int) ->", "not q1_done: index = list(winning_set)[0] s = sum_grid(grids[index], checked_grids[index]) print(\"part1:\",", "range(GRID_SIZE)] for _ in range(len(grids))]) win = False i =", "set of id of the wining grids\"\"\" return set(np.where(check_grids.sum(axis=1).max(axis=1) ==", "checked_grids: np.ndarray, number: int) -> None: checked_grids[np.where(grids == number)] =", "== 1 and not q1_done: index = list(winning_set)[0] s =", "grid[checked_grid] = 0 return grid.sum() def main() -> None: with", "def read_bingo_grid(lines: list[str]) -> list[list[int]]: return [[int(n) for n in", "np GRID_SIZE = 5 def read_bingo_grid(lines: list[str]) -> list[list[int]]: return", "bingo_step(grids, checked_grids, random_numbers[i]) winning_set = check_victory(checked_grids) if len(winning_set) == 1", "def sum_grid(grid: np.ndarray, checked_grid: np.ndarray) -> int: grid[checked_grid] = 0" ]
[ "pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year =", "of age groups within a population. It uses a slider", "alt from altair.expr import datum, if_ from vega_datasets import data", "slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider)", "x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left | middle |", "1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male',", "= base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title,", "right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q',", "data pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year", "= alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base", "category: case studies import altair as alt from altair.expr import", ").encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female')", "visualize the age distribution over time. ''' # category: case", "<filename>altair/vegalite/v2/examples/us_population_pyramid_over_time.py<gh_stars>1-10 ''' US Population Pyramid Over Time =============================== A population", "fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex", "to visualize the age distribution over time. ''' # category:", "alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter(", "axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O',", "base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender ==", "color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender", "is bound to the year to visualize the age distribution", "range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O',", "base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')),", ").mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right =", "= alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left =", "= base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title),", "= alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year", "'#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None),", "datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale,", "bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex ==", "bound to the year to visualize the age distribution over", "=============================== A population pyramid shows the distribution of age groups", "population. It uses a slider widget that is bound to", "to the year to visualize the age distribution over time.", "Time =============================== A population pyramid shows the distribution of age", "vega_datasets import data pop = data.population.url slider = alt.binding_range(min=1850, max=2000,", "axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode(", "axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle =", "'Male', 'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'],", "import datum, if_ from vega_datasets import data pop = data.population.url", ") title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2'])", "alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base =", "select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title =", "US Population Pyramid Over Time =============================== A population pyramid shows", "base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1,", "= base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender", "import data pop = data.population.url slider = alt.binding_range(min=1850, max=2000, step=10)", "select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') )", "groups within a population. It uses a slider widget that", "from altair.expr import datum, if_ from vega_datasets import data pop", "= alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male',", "alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female'", "gender=if_(datum.sex == 1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale", ").encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left", "= data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year',", "pyramid shows the distribution of age groups within a population.", "'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None)", ").mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None),", "It uses a slider widget that is bound to the", "y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male'", "over time. ''' # category: case studies import altair as", "the age distribution over time. ''' # category: case studies", "case studies import altair as alt from altair.expr import datum,", "'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender == 'Female' ).encode(", "Population Pyramid Over Time =============================== A population pyramid shows the", "= alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left = base.transform_filter( datum.gender ==", "axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left | middle | right", "Pyramid Over Time =============================== A population pyramid shows the distribution", "a population. It uses a slider widget that is bound", "# category: case studies import altair as alt from altair.expr", "the year to visualize the age distribution over time. '''", "distribution of age groups within a population. It uses a", "title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4', '#e377c2']) left", "sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None),", "the distribution of age groups within a population. It uses", "'Female') ) title = alt.Axis(title='population') color_scale = alt.Scale(domain=['Male', 'Female'], range=['#1f77b4',", "studies import altair as alt from altair.expr import datum, if_", "max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection(", "alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female')", "step=10) select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year", ").transform_filter( select_year ).transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title", "as alt from altair.expr import datum, if_ from vega_datasets import", "A population pyramid shows the distribution of age groups within", "age groups within a population. It uses a slider widget", ").transform_calculate( gender=if_(datum.sex == 1, 'Male', 'Female') ) title = alt.Axis(title='population')", "altair.expr import datum, if_ from vega_datasets import data pop =", "slider widget that is bound to the year to visualize", "y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left |", "== 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None)", "middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter(", "year to visualize the age distribution over time. ''' #", "population pyramid shows the distribution of age groups within a", "axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male') left | middle", "text=alt.Text('age:Q'), ).mark_text().properties(width=20) right = base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O',", "age distribution over time. ''' # category: case studies import", "uses a slider widget that is bound to the year", "that is bound to the year to visualize the age", "datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N',", "distribution over time. ''' # category: case studies import altair", "''' # category: case studies import altair as alt from", "from vega_datasets import data pop = data.population.url slider = alt.binding_range(min=1850,", "left = base.transform_filter( datum.gender == 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q',", "import altair as alt from altair.expr import datum, if_ from", "''' US Population Pyramid Over Time =============================== A population pyramid", "select_year = alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter(", "base.transform_filter( datum.gender == 'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N',", "== 'Female' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale,", "x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode(", "altair as alt from altair.expr import datum, if_ from vega_datasets", "datum, if_ from vega_datasets import data pop = data.population.url slider", "== 1, 'Male', 'Female') ) title = alt.Axis(title='population') color_scale =", "color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'),", "alt.selection_single(name='year', fields=['year'], bind=slider) base = alt.Chart(pop).add_selection( select_year ).transform_filter( select_year ).transform_calculate(", "if_ from vega_datasets import data pop = data.population.url slider =", "legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20) right", "y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle", "shows the distribution of age groups within a population. It", "time. ''' # category: case studies import altair as alt", "data.population.url slider = alt.binding_range(min=1850, max=2000, step=10) select_year = alt.selection_single(name='year', fields=['year'],", "'Male' ).encode( y=alt.X('age:O', axis=None), x=alt.X('sum(people):Q', axis=title), color=alt.Color('gender:N', scale=color_scale, legend=None) ).mark_bar().properties(title='Male')", "scale=color_scale, legend=None) ).mark_bar().properties(title='Female') middle = base.encode( y=alt.X('age:O', axis=None), text=alt.Text('age:Q'), ).mark_text().properties(width=20)", "within a population. It uses a slider widget that is", "a slider widget that is bound to the year to", "widget that is bound to the year to visualize the", "Over Time =============================== A population pyramid shows the distribution of" ]
[ "('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20,", "class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations =", "django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration):", "import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies", "('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can", "import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core',", "null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),),", "fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name',", "model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True,", "[ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[", "model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires',", "migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies =", "name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),", "verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token',", "models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token',", "[ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now,", "options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),), }, ),", "Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [", "editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True,", "], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),), },", "('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()),", "= [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified',", "('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ],", "models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions': (('view_token', 'Can view", "import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ]", "operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),", "] operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False,", "<reponame>ministryofjustice/mtp-api<gh_stars>1-10 from django.db import migrations, models import django.utils.timezone import model_utils.fields", "django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'),", "from django.db import migrations, models import django.utils.timezone import model_utils.fields class", "serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',),", "('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ('name',), 'permissions':", "editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)),", "verbose_name='modified')), ('name', models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)),", "('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('created',", "migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False,", "models.CharField(max_length=20, primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={", "models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [", "model_utils.fields class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations", "dependencies = [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel(", "'ordering': ('name',), 'permissions': (('view_token', 'Can view token'),), }, ), ]", "primary_key=True, serialize=False)), ('token', models.TextField()), ('expires', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering':", "'0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now,", "= [ ('core', '0003_auto_20180404_1515'), ] operations = [ migrations.CreateModel( name='Token'," ]
[ "= db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): #", "datetime): # self.uuid = uuid # self.payload = payload #", "= db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime):", "# class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid", "%r>' % self.response # # class Logs(db.Model): # id =", "payload # self.datetime = datetime # # def __repr__(self): #", "uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def", "def __repr__(self): return '<Data %r>' % self.response # # class", "Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer)", "Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response =", "class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) # uuid =", "db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload = db.Column(db.Text)", "__repr__(self): return '<Data %r>' % self.response # # class Logs(db.Model):", "class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response", "db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid", "response, datetime): self.uuid = uuid self.response = response self.datetime =", "from palm_tree import db class Data(db.Model): id = db.Column(db.Integer, primary_key=True)", "datetime def __repr__(self): return '<Data %r>' % self.response # #", "= db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self,", "primary_key=True) # uuid = db.Column(db.Integer) # payload = db.Column(db.Text) #", "# self.payload = payload # self.datetime = datetime # #", "uuid = db.Column(db.Integer) # payload = db.Column(db.Text) # datetime =", "datetime # # def __repr__(self): # return '<Data %r>' %", "'<Data %r>' % self.response # # class Logs(db.Model): # id", "self.uuid = uuid # self.payload = payload # self.datetime =", "= db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def __init__(self,", "def __init__(self, uuid, payload, datetime): # self.uuid = uuid #", "# datetime = db.Column(db.DateTime) # # def __init__(self, uuid, payload,", "import db class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid =", "= datetime # # def __repr__(self): # return '<Data %r>'", "= db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime", "return '<Data %r>' % self.response # # class Logs(db.Model): #", "payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def", "uuid, response, datetime): self.uuid = uuid self.response = response self.datetime", "self.response = response self.datetime = datetime def __repr__(self): return '<Data", "self.datetime = datetime def __repr__(self): return '<Data %r>' % self.response", "response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid, response,", "% self.response # # class Logs(db.Model): # id = db.Column(db.Integer,", "db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime =", "response self.datetime = datetime def __repr__(self): return '<Data %r>' %", "# uuid = db.Column(db.Integer) # payload = db.Column(db.Text) # datetime", "self.datetime = datetime # # def __repr__(self): # return '<Data", "db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime) def __init__(self, uuid,", "uuid self.response = response self.datetime = datetime def __repr__(self): return", "uuid # self.payload = payload # self.datetime = datetime #", "# # class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True) #", "datetime = db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid =", "db.Column(db.Integer) # payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) #", "payload, datetime): # self.uuid = uuid # self.payload = payload", "= uuid self.response = response self.datetime = datetime def __repr__(self):", "# # def __repr__(self): # return '<Data %r>' % self.payload", "= db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid = uuid", "__init__(self, uuid, payload, datetime): # self.uuid = uuid # self.payload", "__init__(self, uuid, response, datetime): self.uuid = uuid self.response = response", "= payload # self.datetime = datetime # # def __repr__(self):", "= db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload =", "id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text)", "# # def __init__(self, uuid, payload, datetime): # self.uuid =", "db.Column(db.Text) # datetime = db.Column(db.DateTime) # # def __init__(self, uuid,", "self.payload = payload # self.datetime = datetime # # def", "# self.uuid = uuid # self.payload = payload # self.datetime", "self.uuid = uuid self.response = response self.datetime = datetime def", "datetime): self.uuid = uuid self.response = response self.datetime = datetime", "= db.Column(db.Integer) # payload = db.Column(db.Text) # datetime = db.Column(db.DateTime)", "id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) # payload", "# id = db.Column(db.Integer, primary_key=True) # uuid = db.Column(db.Integer) #", "primary_key=True) uuid = db.Column(db.Integer) response = db.Column(db.Text) datetime = db.Column(db.DateTime)", "# self.datetime = datetime # # def __repr__(self): # return", "self.response # # class Logs(db.Model): # id = db.Column(db.Integer, primary_key=True)", "db.Column(db.DateTime) def __init__(self, uuid, response, datetime): self.uuid = uuid self.response", "# def __init__(self, uuid, payload, datetime): # self.uuid = uuid", "db class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.Integer)", "palm_tree import db class Data(db.Model): id = db.Column(db.Integer, primary_key=True) uuid", "datetime = db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime):", "= uuid # self.payload = payload # self.datetime = datetime", "# payload = db.Column(db.Text) # datetime = db.Column(db.DateTime) # #", "= datetime def __repr__(self): return '<Data %r>' % self.response #", "db.Column(db.DateTime) # # def __init__(self, uuid, payload, datetime): # self.uuid", "def __init__(self, uuid, response, datetime): self.uuid = uuid self.response =", "uuid, payload, datetime): # self.uuid = uuid # self.payload =", "= response self.datetime = datetime def __repr__(self): return '<Data %r>'" ]
[ "format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if", "self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down') self.post_iface_state =", "returned. This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs):", "duplicated results # returned. This helper filter them out @functools.wraps(func)", "= command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if", "'Tried my best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up()", "\"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*',", "\"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config - list or", "'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not", "with preserved order. Required for correct cli table generation :param", "255: yield '.'.join([str(item) for item in range_start]) range_start[i] += 1", "workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple, list)) else", "{0} is down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end):", "'' def iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig',", "*args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if isinstance(args[0],", "iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range", "in range_start]) range_start[i] += 1 else: i += 1 def", "'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout \"\"\" return", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "\"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry", "serializing dhcp options @options = [1,2,3] >>> format_options([1, 2, 3])", "specific language governing permissions and limitations # under the License.", "not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return", "manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config -", "response to first request return [format_answer(response[1], iface) for response in", "# not use this file except in compliance with the", "range_start = split_address(range_start) range_end = split_address(range_end) i = 0 #", "if 'UP' in state_list: return 'UP' else: return 'DOWN' return", "table generation :param item: dict :param columns: list with arbitrary", "ip_address: \\ [int(item) for item in ip_address.split('.')] range_start = split_address(range_start)", "[('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for", "( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return", "iface, rollback=True, retry=3): self.rollback = rollback self.retry = retry self.iface", "ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp", "License. import functools import re import subprocess import sys from", "pass class IfaceState(object): \"\"\"Context manager to control state of iface", "check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface)) else: yield", "range_start[i] == range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for", "('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command):", "in compliance with the License. You may obtain # a", "('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in", "def __exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context manager", "Required for correct cli table generation :param item: dict :param", "def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\",", "You may obtain # a copy of the License at", "else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) ==", "\"\"\"Get specified in columns properties, with preserved order. Required for", "sys.stderr.write('Network for iface {0} is down.'.format( iface)) else: yield iface", "range_start]) range_start[i] += 1 else: i += 1 def get_item_properties(item,", "{0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans =", "0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type, value,", "longer that 4 items while i < 4: # 255", "range_end = split_address(range_end) i = 0 # ipv4 subnet cant", "'192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if isinstance(option,", "= retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state =", "for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does", "limitations # under the License. import functools import re import", "under the License is distributed on an \"AS IS\" BASIS,", "def workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple, list))", "for t in set([tuple(d.items()) for d in resp])) return wrapper", "__enter__(self): for iface, vlans in self.config.iteritems(): vifaces = [] for", "else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate", "ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage", "def get_item_properties(item, columns): \"\"\"Get specified in columns properties, with preserved", "returned by scapy is not in usable format [('message-type', 2),", "vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type, value, trace):", "iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of", "of iface when dhcp checker is running \"\"\" def __init__(self,", "be longer that 4 items while i < 4: #", "end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address", "def format_options(options): \"\"\"Util for serializing dhcp options @options = [1,2,3]", "to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def", "option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = (", "properties, with preserved order. Required for correct cli table generation", "[1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for", "this file except in compliance with the License. You may", "sequence of requests #so ans[0][1] would be response to first", "logic to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext", "\"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\",", "and range_start[i] < 255: yield '.'.join([str(item) for item in range_start])", "subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not", "request return [format_answer(response[1], iface) for response in ans] return formatter", "iface {0} is down.'.format( iface)) else: yield iface def pick_ip(range_start,", "usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end']", "isinstance(option, (tuple, list)): header = option[0] if len(option[1:]) > 1:", "while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "= [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item)", "them out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs)", "# under the License. import functools import re import subprocess", "return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface):", "config): \"\"\"Initialize VlansContext @config - list or tuple of (iface,", "properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for serializing dhcp", "if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def", "-= 1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried my", "= lambda ip_address: \\ [int(item) for item in ip_address.split('.')] range_start", "'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return it's state", "Mirantis, Inc. # # Licensed under the Apache License, Version", "re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', []) if 'UP'", "for key in columns: properties.append(item.get(key, '')) return properties def format_options(options):", "[] for key in columns: properties.append(item.get(key, '')) return properties def", "file except in compliance with the License. You may obtain", "1 else: i += 1 def get_item_properties(item, columns): \"\"\"Get specified", "args[0] ans = func(*args, **kwargs) #scapy stores all sequence of", "dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp response \"\"\"", "order. Required for correct cli table generation :param item: dict", "import functools import re import subprocess import sys from scapy", "under the License. import functools import re import subprocess import", "'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and", "checker is running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback", "state) if search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in", "\"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for", "option) else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options =", "__init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry = retry", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src,", "return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists", "not in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1',", "in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is", "due to network infra on broadcast multiple duplicated results #", "iface = args[0] ans = func(*args, **kwargs) #scapy stores all", "or tuple of (iface, vlan) pairs \"\"\" self.config = config", "under the Apache License, Version 2.0 (the \"License\"); you may", "check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return not command_util(\"ip\", \"link\",", "= [] for key in columns: properties.append(item.get(key, '')) return properties", "lambda ip_address: \\ [int(item) for item in ip_address.split('.')] range_start =", "'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state !=", "return func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due to", "self.post_iface_state = '' def iface_up(self): while self.retry and self.iface_state !=", "dict :param columns: list with arbitrary keys \"\"\" properties =", "'')) return properties def format_options(options): \"\"\"Util for serializing dhcp options", ":param item: dict :param columns: list with arbitrary keys \"\"\"", "manager to control state of iface when dhcp checker is", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object", "'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface)", "[]) if 'UP' in state_list: return 'UP' else: return 'DOWN'", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\"", "to in writing, software # distributed under the License is", "is down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given", "self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry", "1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried my best", "search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', [])", "or agreed to in writing, software # distributed under the", "__exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context manager to", "_iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP': raise EnvironmentError(", "item: dict :param columns: list with arbitrary keys \"\"\" properties", "def __init__(self, config): \"\"\"Initialize VlansContext @config - list or tuple", "required by applicable law or agreed to in writing, software", "self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry and self.iface_state", "import re import subprocess import sys from scapy import all", "command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result:", "infra on broadcast multiple duplicated results # returned. This helper", "iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS,", "resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic to manage", "\"\"\" for option in dhcp_options: if isinstance(option, (tuple, list)): header", "Apache License, Version 2.0 (the \"License\"); you may # not", "list)) else args return func(*args, **kwargs) return workaround def filter_duplicated_results(func):", "if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if", "search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in state_list: return", "split_address = lambda ip_address: \\ [int(item) for item in ip_address.split('.')]", "single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args,", "agreed to in writing, software # distributed under the License", "func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due to network", "control state of iface when dhcp checker is running \"\"\"", "func(*args, **kwargs) #scapy stores all sequence of requests #so ans[0][1]", "distributed under the License is distributed on an \"AS IS\"", "= ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def", "\\ [int(item) for item in ip_address.split('.')] range_start = split_address(range_start) range_end", "else args return func(*args, **kwargs) return workaround def filter_duplicated_results(func): #", "or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "permissions and limitations # under the License. import functools import", "else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options))", "(iface, vlan) pairs \"\"\" self.config = config def __enter__(self): for", "= _iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP': raise", "\"\"\"Contains all logic to manage vlans \"\"\" def __init__(self, config):", "vifaces def __exit__(self, type, value, trace): pass class IfaceState(object): \"\"\"Context", "def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return not", "dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func):", "list)): header = option[0] if len(option[1:]) > 1: yield (header,", "'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def", "if len(option[1:]) > 1: yield (header, option) else: yield (header,", "not use this file except in compliance with the License.", "list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda", "'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check", "state of iface when dhcp checker is running \"\"\" def", "# Copyright 2013 Mirantis, Inc. # # Licensed under the", "generation :param item: dict :param columns: list with arbitrary keys", "writing, software # distributed under the License is distributed on", ":param columns: list with arbitrary keys \"\"\" properties = []", "requests #so ans[0][1] would be response to first request return", "iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up')", "ipv4 subnet cant be longer that 4 items while i", "search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP' else: return", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "subnet if not range_start[i] == range_end[i] and range_start[i] < 255:", "sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "**kwargs): args = args[0] if isinstance(args[0], (tuple, list)) else args", "use this file except in compliance with the License. You", "if not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface))", "tuple of (iface, vlan) pairs \"\"\" self.config = config def", "in ans] return formatter def multiproc_map(func): # multiproc map could", "dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0]", "governing permissions and limitations # under the License. import functools", "\"\"\" split_address = lambda ip_address: \\ [int(item) for item in", "vlan)) yield str(iface), vifaces def __exit__(self, type, value, trace): pass", "255 - end of subnet if not range_start[i] == range_end[i]", "rollback self.retry = retry self.iface = iface self.pre_iface_state = _iface_state(iface)", "format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src,", "next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item) for", "return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return _iface_state(iface) == 'UP'", "return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state !=", "dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'],", "exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface {0} is", "in dhcp_options: if isinstance(option, (tuple, list)): header = option[0] if", "('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if", "self.iface_state != 'UP': raise EnvironmentError( 'Tried my best to ifup", "'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr", "header = option[0] if len(option[1:]) > 1: yield (header, option)", "workaround def filter_duplicated_results(func): # due to network infra on broadcast", "vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "KIND, either express or implied. See the # License for", "4: # 255 - end of subnet if not range_start[i]", "\"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if not", "'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1", "of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address:", "+= 1 def get_item_properties(item, columns): \"\"\"Get specified in columns properties,", "\"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs):", "_iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\"", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "**kwargs) return (dict(t) for t in set([tuple(d.items()) for d in", "provided interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read()", "express or implied. See the # License for the specific", "re import subprocess import sys from scapy import all as", "raise EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface)) def", "in columns properties, with preserved order. Required for correct cli", "the Apache License, Version 2.0 (the \"License\"); you may #", "for correct cli table generation :param item: dict :param columns:", "def formatter(*args, **kwargs): iface = args[0] ans = func(*args, **kwargs)", "= split_address(range_start) range_end = split_address(range_end) i = 0 # ipv4", "helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp =", "dhcp_options: if isinstance(option, (tuple, list)): header = option[0] if len(option[1:])", "yield '.'.join([str(item) for item in range_start]) range_start[i] += 1 else:", "option[0] if len(option[1:]) > 1: yield (header, option) else: yield", "# due to network infra on broadcast multiple duplicated results", "See the # License for the specific language governing permissions", "list or tuple of (iface, vlan) pairs \"\"\" self.config =", "ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\", "_check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return not command_util('which',", "args = args[0] if isinstance(args[0], (tuple, list)) else args return", "return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "\"\"\" return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp", "== range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for item", "formatter def multiproc_map(func): # multiproc map could not work with", "(tuple, list)) else args return func(*args, **kwargs) return workaround def", "the License. import functools import re import subprocess import sys", "\"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "# 255 - end of subnet if not range_start[i] ==", "self.config = config def __enter__(self): for iface, vlans in self.config.iteritems():", "vlans in self.config.iteritems(): vifaces = [] for vlan in vlans:", "stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig():", "if isinstance(option, (tuple, list)): header = option[0] if len(option[1:]) >", "if self.iface_state != 'UP': raise EnvironmentError( 'Tried my best to", "law or agreed to in writing, software # distributed under", "not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface {0}", "properties def format_options(options): \"\"\"Util for serializing dhcp options @options =", "def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback self.retry =", "not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not", "= split_address(range_end) i = 0 # ipv4 subnet cant be", "self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state", "format of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface", "if isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs) return", "keys \"\"\" properties = [] for key in columns: properties.append(item.get(key,", "\"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned", "implied. See the # License for the specific language governing", "def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of ips", "'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with", "value, trace): pass class IfaceState(object): \"\"\"Context manager to control state", "return properties def format_options(options): \"\"\"Util for serializing dhcp options @options", "\"\"\"Util for serializing dhcp options @options = [1,2,3] >>> format_options([1,", "when dhcp checker is running \"\"\" def __init__(self, iface, rollback=True,", "while i < 4: # 255 - end of subnet", "work with format *args @functools.wraps(func) def workaround(*args, **kwargs): args =", "as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport',", "check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided interface", "in columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for", "for vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan))", "if search_result: state_list = search_result.groupdict().get('state', []) if 'UP' in state_list:", "- end of subnet if not range_start[i] == range_end[i] and", "- list or tuple of (iface, vlan) pairs \"\"\" self.config", "network infra on broadcast multiple duplicated results # returned. This", "self.rollback = rollback self.retry = retry self.iface = iface self.pre_iface_state", "for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by", "for serializing dhcp options @options = [1,2,3] >>> format_options([1, 2,", "Inc. # # Licensed under the Apache License, Version 2.0", "config def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces =", "\"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if", "def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not in", "not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in", "t in set([tuple(d.items()) for d in resp])) return wrapper class", "[format_answer(response[1], iface) for response in ans] return formatter def multiproc_map(func):", "split_address(range_start) range_end = split_address(range_end) i = 0 # ipv4 subnet", "return wrapper class VlansContext(object): \"\"\"Contains all logic to manage vlans", "arbitrary keys \"\"\" properties = [] for key in columns:", "= option[0] if len(option[1:]) > 1: yield (header, option) else:", "response in ans] return formatter def multiproc_map(func): # multiproc map", "from scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac',", "dhcp options @options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03'", "command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -= 1 if", "for option in dhcp_options: if isinstance(option, (tuple, list)): header =", "def _iface_state(iface): \"\"\"For a given iface return it's state returns", "does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for iface", "items while i < 4: # 255 - end of", "in state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN' def", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state',", "__init__(self, config): \"\"\"Initialize VlansContext @config - list or tuple of", "of requests #so ans[0][1] would be response to first request", "# # Licensed under the Apache License, Version 2.0 (the", "import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id',", "columns properties, with preserved order. Required for correct cli table", "else: if not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format(", "cli table generation :param item: dict :param columns: list with", "DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message', 'yiaddr')", "ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format", "with format *args @functools.wraps(func) def workaround(*args, **kwargs): args = args[0]", "obtain # a copy of the License at # #", "vifaces = [] for vlan in vlans: if vlan >", "specified in columns properties, with preserved order. Required for correct", "with arbitrary keys \"\"\" properties = [] for key in", "all logic to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize", "i < 4: # 255 - end of subnet if", "iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface):", "Version 2.0 (the \"License\"); you may # not use this", "format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in", "ans[0][1] would be response to first request return [format_answer(response[1], iface)", "vlan) pairs \"\"\" self.config = config def __enter__(self): for iface,", "to network infra on broadcast multiple duplicated results # returned.", "= func(*args, **kwargs) #scapy stores all sequence of requests #so", "scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip',", "list with arbitrary keys \"\"\" properties = [] for key", "generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address =", "= func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items()) for", "rollback=True, retry=3): self.rollback = rollback self.retry = retry self.iface =", "== 'UP' def check_iface_exist(iface): \"\"\"Check provided interface exists \"\"\" return", "it's state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip',", "import subprocess import sys from scapy import all as scapy", "def filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface", "cant be longer that 4 items while i < 4:", "ans = func(*args, **kwargs) #scapy stores all sequence of requests", "__enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if", "License for the specific language governing permissions and limitations #", "'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout \"\"\"", "self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP'", "best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface", "'192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option in dhcp_options:", "to control state of iface when dhcp checker is running", "\"\"\"Initialize VlansContext @config - list or tuple of (iface, vlan)", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "iface when dhcp checker is running \"\"\" def __init__(self, iface,", "all as scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway',", "isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs) return workaround", "'UP': raise EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface))", "= [] for vlan in vlans: if vlan > 0:", "def multiproc_map(func): # multiproc map could not work with format", "self.config.iteritems(): vifaces = [] for vlan in vlans: if vlan", "pairs \"\"\" self.config = config def __enter__(self): for iface, vlans", "start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\"", "of dhcp response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface =", "in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface))", "multiproc map could not work with format *args @functools.wraps(func) def", "item in range_start]) range_start[i] += 1 else: i += 1", "wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t) for t", "in set([tuple(d.items()) for d in resp])) return wrapper class VlansContext(object):", "def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t) for", "ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self,", "columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util for serializing", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options))", "len(option[1:]) > 1: yield (header, option) else: yield (header, option[1])", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check", "resp = func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items())", "not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a", "columns): \"\"\"Get specified in columns properties, with preserved order. Required", "for d in resp])) return wrapper class VlansContext(object): \"\"\"Contains all", "self.retry -= 1 if self.iface_state != 'UP': raise EnvironmentError( 'Tried", "exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig',", "DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result", "0 # ipv4 subnet cant be longer that 4 items", "in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'),", "stores all sequence of requests #so ans[0][1] would be response", "properties = [] for key in columns: properties.append(item.get(key, '')) return", "compliance with the License. You may obtain # a copy", "= args[0] if isinstance(args[0], (tuple, list)) else args return func(*args,", "return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface", "< 4: # 255 - end of subnet if not", "by scapy is not in usable format [('message-type', 2), ('server_id',", "return (dict(t) for t in set([tuple(d.items()) for d in resp]))", "import sys from scapy import all as scapy DHCP_OFFER_COLUMNS =", "def filter_duplicated_results(func): # due to network infra on broadcast multiple", "'192.168.0.2'), 'end'] \"\"\" for option in dhcp_options: if isinstance(option, (tuple,", "multiple duplicated results # returned. This helper filter them out", "\"\"\" self.config = config def __enter__(self): for iface, vlans in", ">>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item", "item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy", "return workaround def filter_duplicated_results(func): # due to network infra on", "item in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i", "the # License for the specific language governing permissions and", "**kwargs) return workaround def filter_duplicated_results(func): # due to network infra", "# # Unless required by applicable law or agreed to", "return it's state returns UP, DOWN, UNKNOWN \"\"\" state =", "(header, option) else: yield (header, option[1]) def format_answer(ans, iface): dhcp_options", "type, value, trace): pass class IfaceState(object): \"\"\"Context manager to control", "filter_duplicated_results(func): # due to network infra on broadcast multiple duplicated", "multiproc_map(func): # multiproc map could not work with format *args", "formatter(*args, **kwargs): iface = args[0] ans = func(*args, **kwargs) #scapy", ">>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item)", "\"\"\"Given start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13')) '192.168.1.10'", "subprocess import sys from scapy import all as scapy DHCP_OFFER_COLUMNS", "results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']],", "return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of dhcp response", "options @options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\"", "filtered_ifaces(ifaces): for iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0}", "subnet cant be longer that 4 items while i <", "check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else: if not check_network_up(iface):", "in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i =", "options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not", "options returned by scapy is not in usable format [('message-type',", "filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args,", "self.retry = retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state", "2.0 (the \"License\"); you may # not use this file", "\"\"\"For a given iface return it's state returns UP, DOWN,", "command_util(*command): \"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE,", "broadcast multiple duplicated results # returned. This helper filter them", "= rollback self.retry = retry self.iface = iface self.pre_iface_state =", "1 def get_item_properties(item, columns): \"\"\"Get specified in columns properties, with", "ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def", "retry=3): self.rollback = rollback self.retry = retry self.iface = iface", "exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces):", "= _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self):", "args return func(*args, **kwargs) return workaround def filter_duplicated_results(func): # due", "response \"\"\" @functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans", "d in resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic", "for iface, vlans in self.config.iteritems(): vifaces = [] for vlan", "range_start[i] += 1 else: i += 1 def get_item_properties(item, columns):", "by applicable law or agreed to in writing, software #", "class IfaceState(object): \"\"\"Context manager to control state of iface when", "VlansContext @config - list or tuple of (iface, vlan) pairs", "return formatter def multiproc_map(func): # multiproc map could not work", "ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not exist.'.format(iface)) else:", "iface return it's state returns UP, DOWN, UNKNOWN \"\"\" state", "@functools.wraps(func) def formatter(*args, **kwargs): iface = args[0] ans = func(*args,", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "> 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self, type,", "vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces", "def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb):", "dhcp checker is running \"\"\" def __init__(self, iface, rollback=True, retry=3):", "@config - list or tuple of (iface, vlan) pairs \"\"\"", "command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given iface return it's", "self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state =", "= self.pre_iface_state self.post_iface_state = '' def iface_up(self): while self.retry and", "return 'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface): return", "self.iface_up() return self.iface def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state", "= config def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces", "command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def filtered_ifaces(ifaces): for iface in ifaces:", "\"\"\"Check vconfig installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read()", "_iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def iface_up(self): while", "args[0] if isinstance(args[0], (tuple, list)) else args return func(*args, **kwargs)", "# multiproc map could not work with format *args @functools.wraps(func)", "!= 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry -=", "map could not work with format *args @functools.wraps(func) def workaround(*args,", "This helper filter them out @functools.wraps(func) def wrapper(*args, **kwargs): resp", "iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return self.iface def __exit__(self, exc_type,", "scapy is not in usable format [('message-type', 2), ('server_id', '192.168.0.5'),", "option in dhcp_options: if isinstance(option, (tuple, list)): header = option[0]", "= dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr,", "may obtain # a copy of the License at #", "wrapper class VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\"", "= iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state =", "in self.config.iteritems(): vifaces = [] for vlan in vlans: if", "Unless required by applicable law or agreed to in writing,", "split_address(range_end) i = 0 # ipv4 subnet cant be longer", "_dhcp_options(dhcp_options): \"\"\"Dhcp options returned by scapy is not in usable", "key in columns: properties.append(item.get(key, '')) return properties def format_options(options): \"\"\"Util", "exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down')", "columns: list with arbitrary keys \"\"\" properties = [] for", "= search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP' else:", "self.iface_state = _iface_state(self.iface) self.retry -= 1 if self.iface_state != 'UP':", "(tuple, list)): header = option[0] if len(option[1:]) > 1: yield", "str(iface), vifaces def __exit__(self, type, value, trace): pass class IfaceState(object):", "installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface):", "in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface),", "results # returned. This helper filter them out @functools.wraps(func) def", "(dict(t) for t in set([tuple(d.items()) for d in resp])) return", "# ipv4 subnet cant be longer that 4 items while", "@functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return (dict(t)", "exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface,", "applicable law or agreed to in writing, software # distributed", "self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = '' def", "__exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and self.rollback:", "yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list", "func(*args, **kwargs) return (dict(t) for t in set([tuple(d.items()) for d", "class VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\" def", "return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options): \"\"\"Dhcp options", "OF ANY KIND, either express or implied. See the #", "running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback = rollback", "with stderr and stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def", "\"\"\"Context manager to control state of iface when dhcp checker", "for response in ans] return formatter def multiproc_map(func): # multiproc", "'\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options)) def _dhcp_options(dhcp_options):", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "for item in range_start]) range_start[i] += 1 else: i +=", "format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\"", "if self.pre_iface_state != 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down') self.post_iface_state", "stdout \"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig", "returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show',", "end of subnet if not range_start[i] == range_end[i] and range_start[i]", "'.'.join([str(item) for item in range_start]) range_start[i] += 1 else: i", "!= 'UP': raise EnvironmentError( 'Tried my best to ifup iface", "set([tuple(d.items()) for d in resp])) return wrapper class VlansContext(object): \"\"\"Contains", "@options = [1,2,3] >>> format_options([1, 2, 3]) '\\x01\\x02\\x03' \"\"\" return", "iface) for response in ans] return formatter def multiproc_map(func): #", "ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results))", "'UP' in state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN'", "1: yield (header, option) else: yield (header, option[1]) def format_answer(ans,", "scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr) return dict(zip(DHCP_OFFER_COLUMNS, results)) def single_format(func): \"\"\"Manage format of", "my best to ifup iface {0}.'.format(self.iface)) def __enter__(self): self.iface_up() return", "yield (header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results", "UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read()", "self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state", "to first request return [format_answer(response[1], iface) for response in ans]", "that 4 items while i < 4: # 255 -", "(header, option[1]) def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results =", "all sequence of requests #so ans[0][1] would be response to", "of subnet if not range_start[i] == range_end[i] and range_start[i] <", "either express or implied. See the # License for the", "ans] return formatter def multiproc_map(func): # multiproc map could not", "format_options(options): \"\"\"Util for serializing dhcp options @options = [1,2,3] >>>", "= args[0] ans = func(*args, **kwargs) #scapy stores all sequence", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "state returns UP, DOWN, UNKNOWN \"\"\" state = command_util('ip', 'link',", "may # not use this file except in compliance with", "first request return [format_answer(response[1], iface) for response in ans] return", "\"\"\" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed", "return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or", "is running \"\"\" def __init__(self, iface, rollback=True, retry=3): self.rollback =", "# License for the specific language governing permissions and limitations", "with the License. You may obtain # a copy of", "functools import re import subprocess import sys from scapy import", "sys from scapy import all as scapy DHCP_OFFER_COLUMNS = ('iface',", "scapy DHCP_OFFER_COLUMNS = ('iface', 'mac', 'server_ip', 'server_id', 'gateway', 'dport', 'message',", "you may # not use this file except in compliance", "out @functools.wraps(func) def wrapper(*args, **kwargs): resp = func(*args, **kwargs) return", "and self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface)", "not check_network_up(iface): sys.stderr.write('Network for iface {0} is down.'.format( iface)) else:", "2), ('server_id', '192.168.0.5'), ('name_server', '192.168.0.1', '192.168.0.2'), 'end'] \"\"\" for option", "yield (header, option) else: yield (header, option[1]) def format_answer(ans, iface):", "**kwargs): resp = func(*args, **kwargs) return (dict(t) for t in", "preserved order. Required for correct cli table generation :param item:", "#so ans[0][1] would be response to first request return [format_answer(response[1],", "[] for vlan in vlans: if vlan > 0: vifaces.append('{0}.{1}'.format(iface,", "VlansContext(object): \"\"\"Contains all logic to manage vlans \"\"\" def __init__(self,", "range_end): \"\"\"Given start_range, end_range generate list of ips >>> next(pick_ip('192.168.1.10','192.168.1.13'))", "def __exit__(self, exc_type, exc_val, exc_tb): if self.pre_iface_state != 'UP' and", "> 1: yield (header, option) else: yield (header, option[1]) def", "range_start[i] < 255: yield '.'.join([str(item) for item in range_start]) range_start[i]", "\"\"\" properties = [] for key in columns: properties.append(item.get(key, ''))", "vlan > 0: vifaces.append('{0}.{1}'.format(iface, vlan)) yield str(iface), vifaces def __exit__(self,", "EnvironmentError( 'Tried my best to ifup iface {0}.'.format(self.iface)) def __enter__(self):", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "\"\"\"Dhcp options returned by scapy is not in usable format", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "return [format_answer(response[1], iface) for response in ans] return formatter def", "in resp])) return wrapper class VlansContext(object): \"\"\"Contains all logic to", "i += 1 def get_item_properties(item, columns): \"\"\"Get specified in columns", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "i = 0 # ipv4 subnet cant be longer that", "results)) def single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func)", "state_list = search_result.groupdict().get('state', []) if 'UP' in state_list: return 'UP'", "Copyright 2013 Mirantis, Inc. # # Licensed under the Apache", "**kwargs): iface = args[0] ans = func(*args, **kwargs) #scapy stores", "def single_format(func): \"\"\"Manage format of dhcp response \"\"\" @functools.wraps(func) def", "ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end) i = 0", "pick_ip(range_start, range_end): \"\"\"Given start_range, end_range generate list of ips >>>", "if not range_start[i] == range_end[i] and range_start[i] < 255: yield", "#scapy stores all sequence of requests #so ans[0][1] would be", "!= 'UP' and self.rollback: command_util('ifconfig', self.iface, 'down') self.post_iface_state = _iface_state(self.iface)", "iface, vlans in self.config.iteritems(): vifaces = [] for vlan in", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "def command_util(*command): \"\"\"object with stderr and stdout \"\"\" return subprocess.Popen(command,", "vconfig installed or not \"\"\" return not command_util('which', 'vconfig').stderr.read() def", "would be response to first request return [format_answer(response[1], iface) for", "retry self.iface = iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state", "for the specific language governing permissions and limitations # under", "and limitations # under the License. import functools import re", "iface self.pre_iface_state = _iface_state(iface) self.iface_state = self.pre_iface_state self.post_iface_state = ''", "for iface {0} is down.'.format( iface)) else: yield iface def", "**kwargs) #scapy stores all sequence of requests #so ans[0][1] would", "'192.168.1.10' \"\"\" split_address = lambda ip_address: \\ [int(item) for item", "{0} does not exist.'.format(iface)) else: if not check_network_up(iface): sys.stderr.write('Network for", "UNKNOWN \"\"\" state = command_util('ip', 'link', 'show', iface).stdout.read() search_result =", "given iface return it's state returns UP, DOWN, UNKNOWN \"\"\"", "'end'] \"\"\" for option in dhcp_options: if isinstance(option, (tuple, list)):", "def format_answer(ans, iface): dhcp_options = dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface,", "except in compliance with the License. You may obtain #", "get_item_properties(item, columns): \"\"\"Get specified in columns properties, with preserved order.", "= 0 # ipv4 subnet cant be longer that 4", "to manage vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config", "= ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport, scapy.DHCPTypes[dhcp_options['message-type']], ans[scapy.BOOTP].yiaddr)", "# returned. This helper filter them out @functools.wraps(func) def wrapper(*args,", "def iface_up(self): while self.retry and self.iface_state != 'UP': command_util('ifconfig', self.iface,", "language governing permissions and limitations # under the License. import", "License. You may obtain # a copy of the License", "'dport', 'message', 'yiaddr') def command_util(*command): \"\"\"object with stderr and stdout", "= re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list = search_result.groupdict().get('state', []) if", "down.'.format( iface)) else: yield iface def pick_ip(range_start, range_end): \"\"\"Given start_range,", "not range_start[i] == range_end[i] and range_start[i] < 255: yield '.'.join([str(item)", "could not work with format *args @functools.wraps(func) def workaround(*args, **kwargs):", "else: i += 1 def get_item_properties(item, columns): \"\"\"Get specified in", "ANY KIND, either express or implied. See the # License", "# distributed under the License is distributed on an \"AS", "def __enter__(self): for iface, vlans in self.config.iteritems(): vifaces = []", "# Unless required by applicable law or agreed to in", "< 255: yield '.'.join([str(item) for item in range_start]) range_start[i] +=", "be response to first request return [format_answer(response[1], iface) for response", "@functools.wraps(func) def workaround(*args, **kwargs): args = args[0] if isinstance(args[0], (tuple,", "on broadcast multiple duplicated results # returned. This helper filter", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "dict(_dhcp_options(ans[scapy.DHCP].options)) results = ( iface, ans[scapy.Ether].src, ans[scapy.IP].src, dhcp_options['server_id'], ans[scapy.BOOTP].giaddr, ans[scapy.UDP].sport,", "'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list =", "not work with format *args @functools.wraps(func) def workaround(*args, **kwargs): args", "for item in ip_address.split('.')] range_start = split_address(range_start) range_end = split_address(range_end)", "4 items while i < 4: # 255 - end", "is not in usable format [('message-type', 2), ('server_id', '192.168.0.5'), ('name_server',", "trace): pass class IfaceState(object): \"\"\"Context manager to control state of", "state_list: return 'UP' else: return 'DOWN' return 'UNKNOWN' def check_network_up(iface):", "'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state) if search_result: state_list", "3]) '\\x01\\x02\\x03' \"\"\" return \"\".join((chr(item) for item in options)) def", "2013 Mirantis, Inc. # # Licensed under the Apache License,", "self.iface_state != 'UP': command_util('ifconfig', self.iface, 'up') self.iface_state = _iface_state(self.iface) self.retry", "stderr=subprocess.PIPE) def _check_vconfig(): \"\"\"Check vconfig installed or not \"\"\" return", "_iface_state(iface): \"\"\"For a given iface return it's state returns UP,", "interface exists \"\"\" return not command_util(\"ip\", \"link\", \"show\", iface).stderr.read() def", "correct cli table generation :param item: dict :param columns: list", "of (iface, vlan) pairs \"\"\" self.config = config def __enter__(self):", "yield str(iface), vifaces def __exit__(self, type, value, trace): pass class", "= '' def iface_up(self): while self.retry and self.iface_state != 'UP':", "def check_network_up(iface): return _iface_state(iface) == 'UP' def check_iface_exist(iface): \"\"\"Check provided", "iface in ifaces: if not check_iface_exist(iface): sys.stderr.write('Iface {0} does not", "a given iface return it's state returns UP, DOWN, UNKNOWN", "state = command_util('ip', 'link', 'show', iface).stdout.read() search_result = re.search(r'.*<(?P<state>.*)>.*', state)", "\"\"\" return not command_util('which', 'vconfig').stderr.read() def _iface_state(iface): \"\"\"For a given", "[int(item) for item in ip_address.split('.')] range_start = split_address(range_start) range_end =", "vlans \"\"\" def __init__(self, config): \"\"\"Initialize VlansContext @config - list", "IfaceState(object): \"\"\"Context manager to control state of iface when dhcp", "+= 1 else: i += 1 def get_item_properties(item, columns): \"\"\"Get", "or implied. See the # License for the specific language", "range_end[i] and range_start[i] < 255: yield '.'.join([str(item) for item in" ]
[ "ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from", "BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from", "from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market", "FactsInDataSchema from schemas.market import MarketSchema from schemas.period import PeriodSchema class", "= ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only =", "= ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model =", "class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category =", "model = JohnsonScannerDataModel dump_only = (\"id\",) # include_fk = False", "import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema", "import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market =", "import FactsInDataSchema from schemas.market import MarketSchema from schemas.period import PeriodSchema", "import ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema", "models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import", "from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period", "= ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts =", "ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema)", "= ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period =", "import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema", "from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category", "ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta:", "period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model", "schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from schemas.period import", "JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import CategorySchema from", "from schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data", "class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",) # include_fk", "from schemas.market import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema):", "ma import ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand import", "PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category", "JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema)", "schemas.category import CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import", "facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only", "schemas.market import MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market", "schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand =", "brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts", "from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand", "Meta: model = JohnsonScannerDataModel dump_only = (\"id\",) # include_fk =", "schemas.brand import BrandSchema from schemas.category import CategorySchema from schemas.facts_in_data import", "import JohnsonScannerDataModel from schemas.brand import BrandSchema from schemas.category import CategorySchema", "market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period", "from ma import ma from models.johnson_scanner_data import JohnsonScannerDataModel from schemas.brand", "import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema) brand = ma.Nested(BrandSchema)", "category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True)", "MarketSchema from schemas.period import PeriodSchema class JohnsonScannerDataSchema(ma.SQLAlchemySchema): market = ma.Nested(MarketSchema)", "= ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class", "ma.Nested(BrandSchema) category = ma.Nested(CategorySchema) period = ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema,", "many=True) class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",) #", "ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel dump_only = (\"id\",)", "ma.Nested(PeriodSchema) facts = ma.Nested(FactsInDataSchema, many=True) class Meta: model = JohnsonScannerDataModel", "CategorySchema from schemas.facts_in_data import FactsInDataSchema from schemas.market import MarketSchema from" ]
[ "################################################################################ # PyTorch and neural network imports import torch from", "the class predictions #TODO: apply an activition function to 'batch'", "Fill in the remaining initializations replacing each '_' with #", "the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights", "self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the", "dataloader import torchvision from torchvision import transforms, utils from xray_dataloader_zscored", "Return the class predictions #TODO: apply an activition function to", "= inputs.size()[1:] # Track the number of features num_features =", "batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to", "channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3)", "the network \"\"\" # Apply first convolution, followed by ReLU", "self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed", "output of conv3 to the pooling layer batch = self.pool5(batch)", "batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this", "max-pooling with a [3x3] kernel using tiling (*NO SLIDING WINDOW*)", "Define 2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8,", "this layer is slightly different than the rest (why?) batch", "= nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 =", "# Be sure to fill in the code in the", "import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim", "xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight)", "# In[ ]: ################################################################################ # CSE 253: Programming Assignment 3", "-> fc1 -> fc2 -> fc3 (outputs) ======= conv1 ->", "-> conv2 -> maxpool -> conv3 -> conv4 -> conv5", "# conv1: 1 input channel, 4 output channels, [3x3] kernel", "for each layer #TODO: conv2: 4 input channels, 8 output", "inputs size = inputs.size()[1:] # Track the number of features", "conv4: X input channels, 10 output channels, [6x6] kernel, initialization:", "<<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool ->", "kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed =", "= 14 def forward(self, batch): \"\"\"Pass the batch of images", "- this layer is slightly different than the rest (why?)", "for the baseline architecture you will use # to get", "to get a little practice with PyTorch and compare the", "the layers excluding the inputs size = inputs.size()[1:] # Track", "conv6 -> maxpool -> conv7 -> conv8 -> maxpool ->", "======= conv1 -> conv2 -> maxpool -> conv3 -> conv4", "conv5 -> conv6 -> maxpool -> conv7 -> conv8 ->", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling", "channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2 =", "practice with PyTorch and compare the results of with your", "the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch =", "= func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch =", "nn import torch.nn.functional as func import torch.nn.init as torch_init import", "func import torch.nn.init as torch_init import torch.optim as optim #", "func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the pooling", "self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply", "3 # Winter 2019 # Code author: <NAME> (+ modifications", "-> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\"", "-> conv2 -> maxpool -> conv3 -> conv4 ->maxpool ->", "-> maxpool -> conv7 -> conv8 -> maxpool -> fc1", "import torchvision from torchvision import transforms, utils from xray_dataloader_zscored import", "kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed =", "fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what", "torch from torch.autograd import Variable import torch.nn as nn import", "nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 =", "applying non-linearities after each layer. Note that this function *needs*", "outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using", "use # to get a little practice with PyTorch and", "\"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel,", "conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch =", "channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3 =", "is slightly different than the rest (why?) batch = self.fc3(batch)", "create_split_loaders import matplotlib.pyplot as plt import numpy as np import", "contains the starter code for the baseline architecture you will", "function *needs* to be called \"forward\" for PyTorch to automagically", "fc2 -> fc3 (outputs) ======= conv1 -> conv2 -> maxpool", "self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3]", "initializations replacing each '_' with # the necessary value based", "output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16,", "import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as", "#TODO: conv5: X input channels, 8 output channels, [5x5] kernel,", "#TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight)", "output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16,", "self.fc3(batch) # Return the class predictions #TODO: apply an activition", "areas marked #TODO. ################################################################################ # PyTorch and neural network imports", "#TODO: conv3: X input channels, 12 output channels, [8x8] kernel,", "# # Be sure to fill in the code in", "torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected", "Params: ------- - batch: (Tensor) An input batch of images", "-> maxpool -> conv3 -> conv4 -> conv5 -> maxpool", "of conv3 to the pooling layer batch = self.pool4(batch) batch", "batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output", "out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4)", "SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8)", "batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of", "numpy as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD", "CSE 253: Programming Assignment 3 # Winter 2019 # Code", "self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations", "self.pool5(batch) # Reshape the output of the conv3 to pass", "baseline_cnn.py # # Description: # # This file contains the", "------- - batch: (Tensor) An input batch of images Returns:", "out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128,", "a little practice with PyTorch and compare the results of", "Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in", "import torch.nn.init as torch_init import torch.optim as optim # Data", "# Track the number of features num_features = 1 for", "on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) #", "batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch", "neural network imports import torch from torch.autograd import Variable import", "self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2", "(Variable) The output of the network \"\"\" # Apply first", "import torch from torch.autograd import Variable import torch.nn as nn", "author: <NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py", "each layer. Note that this function *needs* to be called", "self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "= func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to the", "1 input channel, 4 output channels, [3x3] kernel size self.conv1", "func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer is", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing", "# This file contains the starter code for the baseline", "the batch of images through each layer of the network,", "torch.nn.init as torch_init import torch.optim as optim # Data utils", "self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO:", "called \"forward\" for PyTorch to automagically perform the forward pass.", "\"\"\" # Apply first convolution, followed by ReLU non-linearity; #", "# improved architecture. # # Be sure to fill in", "self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8", "= nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 =", "stride=1) #TODO: Fill in the remaining initializations replacing each '_'", "torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output", "kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed =", "- batch: (Tensor) An input batch of images Returns: --------", "stride=1) #TODO: conv3: X input channels, 12 output channels, [8x8]", "conv7 -> conv8 -> maxpool -> fc1 -> fc2 ->", "= func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch =", "ReLU non-linearity; # use batch-normalization on its outputs batch =", "batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch", "improved architecture. # # Be sure to fill in the", "Description: # # This file contains the starter code for", "batch of images through each layer of the network, applying", "[8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed", "# CSE 253: Programming Assignment 3 # Winter 2019 #", "import torch.nn as nn import torch.nn.functional as func import torch.nn.init", "(outputs) ======= conv1 -> conv2 -> maxpool -> conv3 ->", "based on the provided specs for each layer #TODO: conv2:", "batch): \"\"\"Pass the batch of images through each layer of", "channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3)", "import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool", "nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8,", "Get the dimensions of the layers excluding the inputs size", "# to get a little practice with PyTorch and compare", "layer batch = self.pool5(batch) # Reshape the output of the", "with your # improved architecture. # # Be sure to", "output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8,", "the pooling layer batch = self.pool5(batch) # Reshape the output", "of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch", "= nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel using", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output", "#TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer:", ">>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1", "################################################################################ # CSE 253: Programming Assignment 3 # Winter 2019", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3:", "func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the pooling", "network \"\"\" # Apply first convolution, followed by ReLU non-linearity;", "self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6", "imports import torch from torch.autograd import Variable import torch.nn as", "4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4,", "(why?) batch = self.fc3(batch) # Return the class predictions #TODO:", "Add batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4)", "-> fc2 -> fc3 (outputs) ======= conv1 -> conv2 ->", "as optim # Data utils and dataloader import torchvision from", "# Connect fc1 to fc2 - this layer is slightly", "8 output channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16,", "# use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch", "nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed =", "that this function *needs* to be called \"forward\" for PyTorch", "= nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully", "channel, 4 output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1,", "self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5", "batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3 to", "of images Returns: -------- - logits: (Variable) The output of", "fc3 (outputs) ======= conv1 -> conv2 -> maxpool -> conv3", "channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4 =", "code in the areas marked #TODO. ################################################################################ # PyTorch and", "each '_' with # the necessary value based on the", "Apply first convolution, followed by ReLU non-linearity; # use batch-normalization", "= nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight)", "to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized", "HEAD conv1 -> maxpool -> conv2 -> maxpool -> conv3", "matplotlib.pyplot as plt import numpy as np import os class", "input channels, 8 output channels, [3x3] kernel, initialization: xavier self.conv2", "utf-8 # In[ ]: ################################################################################ # CSE 253: Programming Assignment", "ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy as np", "torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128)", "<NAME>) # # Filename: baseline_cnn.py # # Description: # #", "253: Programming Assignment 3 # Winter 2019 # Code author:", "input batch of images Returns: -------- - logits: (Variable) The", "automagically perform the forward pass. Params: ------- - batch: (Tensor)", "func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch)))", "= func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the", "#TODO: Fill in the remaining initializations replacing each '_' with", "WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight)", "self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4", "[6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed", "fc1 to fc2 - this layer is slightly different than", "= nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight)", "the network, applying non-linearities after each layer. Note that this", "channels, [5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3)", "replacing each '_' with # the necessary value based on", "->maxpool -> conv5 -> conv6 -> maxpool -> conv7 ->", "torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight)", "self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the", "of the network \"\"\" # Apply first convolution, followed by", "= func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3 to the", "nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of", "batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) #", "= self.pool1(batch) # Apply conv2 and conv3 similarly batch =", "torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight)", "Returns: -------- - logits: (Variable) The output of the network", "= nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 =", "of with your # improved architecture. # # Be sure", "Programming Assignment 3 # Winter 2019 # Code author: <NAME>", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8)", "kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed =", "#TODO: Apply max-pooling with a [3x3] kernel using tiling (*NO", "# Description: # # This file contains the starter code", "forward pass. Params: ------- - batch: (Tensor) An input batch", "the output of conv3 to the pooling layer batch =", "'_' with # the necessary value based on the provided", "= nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2", "out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input", "self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128)", "as torch_init import torch.optim as optim # Data utils and", "Winter 2019 # Code author: <NAME> (+ modifications by <NAME>)", "-> maxpool -> conv3 -> conv4 ->maxpool -> conv5 ->", "conv4 ->maxpool -> conv5 -> conv6 -> maxpool -> conv7", "import numpy as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<<", "the necessary value based on the provided specs for each", "Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3,", "layer #TODO: conv2: 4 input channels, 8 output channels, [3x3]", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output", "= self.fc3(batch) # Return the class predictions #TODO: apply an", "6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input", "xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import numpy", "to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect", "nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8,", "torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as", "# Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch", "output of the conv3 to pass to fully-connected layer batch", "through each layer of the network, applying non-linearities after each", "channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) #", "func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get the dimensions", "with # the necessary value based on the provided specs", "layer is slightly different than the rest (why?) batch =", "torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import", "= nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4:", "and neural network imports import torch from torch.autograd import Variable", "from torch.autograd import Variable import torch.nn as nn import torch.nn.functional", "-> conv8 -> maxpool -> fc1 -> fc2 -> fc3", "-> fc3 (outputs) ======= conv1 -> conv2 -> maxpool ->", "func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch)))", "nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4,", "fc2 - this layer is slightly different than the rest", "= func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2", "*needs* to be called \"forward\" for PyTorch to automagically perform", "conv3 -> conv4 -> conv5 -> maxpool -> fc1 ->", "torchvision from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset,", "layer: what should out_features be? self.out_features = 14 def forward(self,", "#TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight)", "X input channels, 10 output channels, [6x6] kernel, initialization: xavier", "self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define", "nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be?", "torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a", "of the conv3 to pass to fully-connected layer batch =", "method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the", "nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 =", "be? self.out_features = 14 def forward(self, batch): \"\"\"Pass the batch", "torch_init import torch.optim as optim # Data utils and dataloader", "fill in the code in the areas marked #TODO. ################################################################################", "# # Filename: baseline_cnn.py # # Description: # # This", "initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8)", "out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8,", "layer. Note that this function *needs* to be called \"forward\"", "batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output", "self.num_flat_features(batch)) # Connect the reshaped features of the pooled conv3", "self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool", "as func import torch.nn.init as torch_init import torch.optim as optim", "the baseline architecture you will use # to get a", "12 output channels, [8x8] kernel, initialization: xavier self.conv3 = nn.Conv2d(in_channels=8,", "= batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the", "conv8 -> maxpool -> fc1 -> fc2 -> fc3 (outputs)", "by <NAME>) # # Filename: baseline_cnn.py # # Description: #", "input channels, 10 output channels, [6x6] kernel, initialization: xavier self.conv4", "little practice with PyTorch and compare the results of with", "number of features num_features = 1 for s in size:", "using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "# PyTorch and neural network imports import torch from torch.autograd", "torch.autograd import Variable import torch.nn as nn import torch.nn.functional as", "kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed =", "input channel, 4 output channels, [3x3] kernel size self.conv1 =", "conv2: 4 input channels, 8 output channels, [3x3] kernel, initialization:", "self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should", "An input batch of images Returns: -------- - logits: (Variable)", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8 output channels,", "excluding the inputs size = inputs.size()[1:] # Track the number", "optim # Data utils and dataloader import torchvision from torchvision", "provided specs for each layer #TODO: conv2: 4 input channels,", "torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels,", "= func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of", "(Tensor) An input batch of images Returns: -------- - logits:", "predictions #TODO: apply an activition function to 'batch' #batch =", "= nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 =", "-> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self):", "batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch", "= func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 - this layer", "class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2", "out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1)", "pass. Params: ------- - batch: (Tensor) An input batch of", "the output of the conv3 to pass to fully-connected layer", "Be sure to fill in the code in the areas", "kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) #", "the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed =", "Note that this function *needs* to be called \"forward\" for", "sure to fill in the code in the areas marked", "import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot", "2019 # Code author: <NAME> (+ modifications by <NAME>) #", "# # Description: # # This file contains the starter", "self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5:", "# Winter 2019 # Code author: <NAME> (+ modifications by", "kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO:", "Reshape the output of the conv3 to pass to fully-connected", "specs for each layer #TODO: conv2: 4 input channels, 8", "the dimensions of the layers excluding the inputs size =", "remaining initializations replacing each '_' with # the necessary value", "batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch", "num_features = 1 for s in size: num_features *= s", "initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8)", "fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def", "after each layer. Note that this function *needs* to be", "layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features", "Variable import torch.nn as nn import torch.nn.functional as func import", "= self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass", "def forward(self, batch): \"\"\"Pass the batch of images through each", "output channels, [3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3)", "as plt import numpy as np import os class Arch2CNN(nn.Module):", "to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the", "initialization: xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16)", "initialization: xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16)", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X", "self).__init__() # conv1: 1 input channel, 4 output channels, [3x3]", "# Code author: <NAME> (+ modifications by <NAME>) # #", "torch.optim as optim # Data utils and dataloader import torchvision", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed =", "fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed", "[3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8,", "the rest (why?) batch = self.fc3(batch) # Return the class", "self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10", "#TODO. ################################################################################ # PyTorch and neural network imports import torch", "conv2 -> maxpool -> conv3 -> conv4 -> conv5 ->", "PyTorch to automagically perform the forward pass. Params: ------- -", "inputs.size()[1:] # Track the number of features num_features = 1", "size = inputs.size()[1:] # Track the number of features num_features", "nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X", "torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining", "-------- - logits: (Variable) The output of the network \"\"\"", "from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt import", "torch.nn as nn import torch.nn.functional as func import torch.nn.init as", "conv3 to the pooling layer batch = self.pool4(batch) batch =", "conv2 -> maxpool -> conv3 -> conv4 ->maxpool -> conv5", "kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization", "= nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO:", "= func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch =", "each layer #TODO: conv2: 4 input channels, 8 output channels,", "slightly different than the rest (why?) batch = self.fc3(batch) #", "coding: utf-8 # In[ ]: ################################################################################ # CSE 253: Programming", "self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14)", "inputs): # Get the dimensions of the layers excluding the", "# Apply first convolution, followed by ReLU non-linearity; # use", "xavier self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight)", "the reshaped features of the pooled conv3 to fc1 batch", "__init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output", "batch-normalization to the outputs of conv1 self.conv1_normed = nn.BatchNorm2d(4) #", "features num_features = 1 for s in size: num_features *=", "python # coding: utf-8 # In[ ]: ################################################################################ # CSE", "utils and dataloader import torchvision from torchvision import transforms, utils", "and dataloader import torchvision from torchvision import transforms, utils from", "to fill in the code in the areas marked #TODO.", "(+ modifications by <NAME>) # # Filename: baseline_cnn.py # #", "to automagically perform the forward pass. Params: ------- - batch:", "The output of the network \"\"\" # Apply first convolution,", "14 def forward(self, batch): \"\"\"Pass the batch of images through", "value based on the provided specs for each layer #TODO:", "to the pooling layer batch = self.pool5(batch) # Reshape the", "batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped features of the pooled", "# Connect the reshaped features of the pooled conv3 to", "-> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__()", "]: ################################################################################ # CSE 253: Programming Assignment 3 # Winter", "conv3 -> conv4 ->maxpool -> conv5 -> conv6 -> maxpool", "for PyTorch to automagically perform the forward pass. Params: -------", "import Variable import torch.nn as nn import torch.nn.functional as func", "-> maxpool -> fc1 -> fc2 -> fc3 (outputs) =======", "# Filename: baseline_cnn.py # # Description: # # This file", "-> conv7 -> conv8 -> maxpool -> fc1 -> fc2", "as nn import torch.nn.functional as func import torch.nn.init as torch_init", "import torch.optim as optim # Data utils and dataloader import", "code for the baseline architecture you will use # to", "the conv3 to pass to fully-connected layer batch = batch.view(-1,", "self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed", "super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4 output channels,", "each layer of the network, applying non-linearities after each layer.", "self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method", "pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch)))", "batch def num_flat_features(self, inputs): # Get the dimensions of the", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12 output channels,", "out_channels=8, kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8,", "batch = self.fc3(batch) # Return the class predictions #TODO: apply", "should out_features be? self.out_features = 14 def forward(self, batch): \"\"\"Pass", "maxpool -> conv7 -> conv8 -> maxpool -> fc1 ->", "pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect", "similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch)))", "Code author: <NAME> (+ modifications by <NAME>) # # Filename:", "function to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self,", "utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as plt", "conv5: X input channels, 8 output channels, [5x5] kernel, initialization:", "In[ ]: ################################################################################ # CSE 253: Programming Assignment 3 #", "conv5 -> maxpool -> fc1 -> fc2 -> fc3 (outputs)", "= nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with a [3x3] kernel", "as np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1", "out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1)", "to 'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs):", "the number of features num_features = 1 for s in", "in the code in the areas marked #TODO. ################################################################################ #", "output of conv3 to the pooling layer batch = self.pool4(batch)", "= nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed", "2 fully connected layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512)", "-> conv4 -> conv5 -> maxpool -> fc1 -> fc2", "size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to", "nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3,", "the remaining initializations replacing each '_' with # the necessary", "fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1", "<NAME> (+ modifications by <NAME>) # # Filename: baseline_cnn.py #", "conv1: 1 input channel, 4 output channels, [3x3] kernel size", "maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6", "you will use # to get a little practice with", "Pass the output of conv3 to the pooling layer batch", "func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch) batch = func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch)))", "baseline architecture you will use # to get a little", "a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7 =", "channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3)", "of the layers excluding the inputs size = inputs.size()[1:] #", "get a little practice with PyTorch and compare the results", "network, applying non-linearities after each layer. Note that this function", "Connect fc1 to fc2 - this layer is slightly different", "self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input channels, 8", "torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features =", "-> conv5 -> conv6 -> maxpool -> conv7 -> conv8", "= 1 for s in size: num_features *= s return", "starter code for the baseline architecture you will use #", "torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels, [6x6]", "-> conv5 -> maxpool -> fc1 -> fc2 -> fc3", "class predictions #TODO: apply an activition function to 'batch' #batch", "nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X input", "of conv3 to the pooling layer batch = self.pool5(batch) #", "Assignment 3 # Winter 2019 # Code author: <NAME> (+", "layers: #TODO: fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512)", "self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3", "logits: (Variable) The output of the network \"\"\" # Apply", "kernel using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8,", "= nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv5: X", "first convolution, followed by ReLU non-linearity; # use batch-normalization on", "stride=4) # Define 2 fully connected layers: #TODO: fc1 self.fc1", "# # This file contains the starter code for the", "[5x5] kernel, initialization: xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed", "layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch)))", "fc1 self.fc1 = nn.Linear(in_features=122*122*8, out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO:", "stride=1) #TODO: Apply max-pooling with a [3x3] kernel using tiling", "# Add batch-normalization to the outputs of conv1 self.conv1_normed =", "\"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2 -> maxpool", "stride=1) #TODO: conv5: X input channels, 8 output channels, [5x5]", "conv4 -> conv5 -> maxpool -> fc1 -> fc2 ->", "self.out_features = 14 def forward(self, batch): \"\"\"Pass the batch of", "return batch def num_flat_features(self, inputs): # Get the dimensions of", "-> conv3 -> conv4 -> conv5 -> maxpool -> fc1", "kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1)", "# Data utils and dataloader import torchvision from torchvision import", "conv1 -> maxpool -> conv2 -> maxpool -> conv3 ->", "X input channels, 8 output channels, [5x5] kernel, initialization: xavier", "on the provided specs for each layer #TODO: conv2: 4", "# coding: utf-8 # In[ ]: ################################################################################ # CSE 253:", "using tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3)", "batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch)", "fc2 -> fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN,", "# the necessary value based on the provided specs for", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Apply max-pooling with", "self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add batch-normalization to the", "out_channels=4, kernel_size=3) # Add batch-normalization to the outputs of conv1", "out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3,", "batch = self.pool1(batch) # Apply conv2 and conv3 similarly batch", "8 output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4,", "maxpool -> conv2 -> maxpool -> conv3 -> conv4 ->maxpool", "activition function to 'batch' #batch = func.sigmoid(batch) return batch def", "= nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv8_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 =", "nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers: #TODO: fc1", "#TODO: Output layer: what should out_features be? self.out_features = 14", "Connect the reshaped features of the pooled conv3 to fc1", "np import os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 ->", "and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch) batch", "non-linearity; # use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch)))", "def __init__(self): super(Arch2CNN, self).__init__() # conv1: 1 input channel, 4", "to be called \"forward\" for PyTorch to automagically perform the", "will use # to get a little practice with PyTorch", "4 input channels, 8 output channels, [3x3] kernel, initialization: xavier", "# Reshape the output of the conv3 to pass to", "pooling layer batch = self.pool5(batch) # Reshape the output of", "Apply max-pooling with a [3x3] kernel using tiling (*NO SLIDING", "with a [3x3] kernel using tiling (*NO SLIDING WINDOW*) self.conv7", "of conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the", "self.pool1(batch) # Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch)))", "layers excluding the inputs size = inputs.size()[1:] # Track the", "fc3 (outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() #", "and compare the results of with your # improved architecture.", "use batch-normalization on its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch =", "# Return the class predictions #TODO: apply an activition function", "= nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features", "file contains the starter code for the baseline architecture you", "maxpool -> conv3 -> conv4 -> conv5 -> maxpool ->", "network imports import torch from torch.autograd import Variable import torch.nn", "fc1 -> fc2 -> fc3 (outputs) ======= conv1 -> conv2", "in the remaining initializations replacing each '_' with # the", "# Get the dimensions of the layers excluding the inputs", "fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) # Connect the reshaped", "maxpool -> fc1 -> fc2 -> fc3 (outputs) ======= conv1", "# Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 =", "\"\"\"Pass the batch of images through each layer of the", "pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch =", "func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass the output of conv3", "-> conv4 ->maxpool -> conv5 -> conv6 -> maxpool ->", "reshaped features of the pooled conv3 to fc1 batch =", "[3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed", "self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch = self.pool3(batch)", "batch: (Tensor) An input batch of images Returns: -------- -", "conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) #", "the code in the areas marked #TODO. ################################################################################ # PyTorch", "the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill", "conv3 to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch))", "This file contains the starter code for the baseline architecture", "X input channels, 12 output channels, [8x8] kernel, initialization: xavier", "maxpool -> conv3 -> conv4 ->maxpool -> conv5 -> conv6", "architecture. # # Be sure to fill in the code", "# Pass the output of conv3 to the pooling layer", "(outputs) >>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 \"\"\" def __init__(self): super(Arch2CNN, self).__init__() # conv1:", "to the pooling layer batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch)))", "self.conv4 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3) self.conv4_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv4.weight) self.pool3", "to fc2 - this layer is slightly different than the", "(*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed =", "func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to fc2 -", "weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1 = nn.MaxPool2d(kernel_size=3, stride=1)", "#Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels,", "-> maxpool -> conv2 -> maxpool -> conv3 -> conv4", "= nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv8.weight) self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2", "os class Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool ->", "transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders import matplotlib.pyplot as", "= func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3", "# Define 2 fully connected layers: #TODO: fc1 self.fc1 =", "fc2 self.fc2 = nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO:", "images through each layer of the network, applying non-linearities after", "followed by ReLU non-linearity; # use batch-normalization on its outputs", "batch = func.rrelu(self.fc1_normed(self.fc1(batch))) batch = func.rrelu(self.fc2_normed(self.fc2(batch))) # Connect fc1 to", "= nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output", "from torchvision import transforms, utils from xray_dataloader_zscored import ChestXrayDataset, create_split_loaders", "Data utils and dataloader import torchvision from torchvision import transforms,", "torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input", "#batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): # Get", "batch = self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) #", "results of with your # improved architecture. # # Be", "an activition function to 'batch' #batch = func.sigmoid(batch) return batch", "architecture you will use # to get a little practice", "the starter code for the baseline architecture you will use", "batch of images Returns: -------- - logits: (Variable) The output", "apply an activition function to 'batch' #batch = func.sigmoid(batch) return", "#TODO: conv2: 4 input channels, 8 output channels, [3x3] kernel,", "layer of the network, applying non-linearities after each layer. Note", "batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and", "-> maxpool -> fc1 -> fc2 -> fc3 (outputs) >>>>>>>", "than the rest (why?) batch = self.fc3(batch) # Return the", "conv1 -> conv2 -> maxpool -> conv3 -> conv4 ->", "def num_flat_features(self, inputs): # Get the dimensions of the layers", "perform the forward pass. Params: ------- - batch: (Tensor) An", "PyTorch and compare the results of with your # improved", "1 for s in size: num_features *= s return num_features", "= self.pool2(batch) batch = func.rrelu(self.conv3_normed(self.conv3(batch))) batch = func.rrelu(self.conv4_normed(self.conv4(batch))) batch =", "-> conv6 -> maxpool -> conv7 -> conv8 -> maxpool", "Arch2CNN(nn.Module): \"\"\" <<<<<<< HEAD conv1 -> maxpool -> conv2 ->", "kernel_size=3) # Add batch-normalization to the outputs of conv1 self.conv1_normed", "import matplotlib.pyplot as plt import numpy as np import os", "kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3)", "different than the rest (why?) batch = self.fc3(batch) # Return", "-> conv3 -> conv4 ->maxpool -> conv5 -> conv6 ->", "of the network, applying non-linearities after each layer. Note that", "xavier self.conv3 = nn.Conv2d(in_channels=8, out_channels=16, kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight)", "func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of conv3", "the areas marked #TODO. ################################################################################ # PyTorch and neural network", "by ReLU non-linearity; # use batch-normalization on its outputs batch", "out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO: Output layer: what should out_features be? self.out_features", "with PyTorch and compare the results of with your #", "nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv6.weight) self.pool4 = nn.MaxPool2d(kernel_size=3,", "forward(self, batch): \"\"\"Pass the batch of images through each layer", "outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2", "its outputs batch = func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply", "self.pool2 = nn.MaxPool2d(kernel_size=3, stride=1) #TODO: conv3: X input channels, 12", "Filename: baseline_cnn.py # # Description: # # This file contains", "modifications by <NAME>) # # Filename: baseline_cnn.py # # Description:", "= func.rrelu(self.conv5_normed(self.conv5(batch))) batch = func.rrelu(self.conv6_normed(self.conv6(batch))) # Pass the output of", "kernel_size=3) self.conv7_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv7.weight) self.conv8 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3)", "self.pool5 = nn.MaxPool2d(kernel_size=4, stride=4) # Define 2 fully connected layers:", "num_flat_features(self, inputs): # Get the dimensions of the layers excluding", "output channels, [3x3] kernel, initialization: xavier self.conv2 = nn.Conv2d(in_channels=4, out_channels=8,", "input channels, 12 output channels, [8x8] kernel, initialization: xavier self.conv3", "kernel_size=3) self.conv3_normed = nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels,", "Apply conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch =", "nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3 = nn.Linear(in_features=128, out_features=14) torch_init.xavier_normal_(self.fc3.weight) #TODO:", "conv3: X input channels, 12 output channels, [8x8] kernel, initialization:", "nn.BatchNorm2d(16) torch_init.xavier_normal_(self.conv3.weight) #TODO: conv4: X input channels, 10 output channels,", "out_features=512) self.fc1_normed = nn.BatchNorm1d(512) torch_init.xavier_normal_(self.fc1.weight) #TODO: fc2 self.fc2 = nn.Linear(in_features=512,", "#!/usr/bin/env python # coding: utf-8 # In[ ]: ################################################################################ #", "input channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5", "of features num_features = 1 for s in size: num_features", "nn.MaxPool2d(kernel_size=3, stride=1) #TODO: Fill in the remaining initializations replacing each", "your # improved architecture. # # Be sure to fill", "xavier self.conv5 = nn.Conv2d(in_channels=16, out_channels=8, kernel_size=3) self.conv5_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight)", "= self.pool5(batch) # Reshape the output of the conv3 to", "be called \"forward\" for PyTorch to automagically perform the forward", "features of the pooled conv3 to fc1 batch = func.rrelu(self.fc1_normed(self.fc1(batch)))", "dimensions of the layers excluding the inputs size = inputs.size()[1:]", "images Returns: -------- - logits: (Variable) The output of the", "non-linearities after each layer. Note that this function *needs* to", "out_features be? self.out_features = 14 def forward(self, batch): \"\"\"Pass the", "#TODO: apply an activition function to 'batch' #batch = func.sigmoid(batch)", "channels, 8 output channels, [5x5] kernel, initialization: xavier self.conv5 =", "conv2 and conv3 similarly batch = func.rrelu(self.conv2_normed(self.conv2(batch))) batch = self.pool2(batch)", "nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3) self.conv2_normed = nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv2.weight) #Maxpool self.pool2 =", "[3x3] kernel size self.conv1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3) # Add", "Track the number of features num_features = 1 for s", "Output layer: what should out_features be? self.out_features = 14 def", "#TODO: conv4: X input channels, 10 output channels, [6x6] kernel,", "the results of with your # improved architecture. # #", "tiling (*NO SLIDING WINDOW*) self.conv7 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv7_normed", "compare the results of with your # improved architecture. #", "nn.BatchNorm2d(8) torch_init.xavier_normal_(self.conv5.weight) self.conv6 = nn.Conv2d(in_channels=8, out_channels=8, kernel_size=3) self.conv6_normed = nn.BatchNorm2d(8)", "necessary value based on the provided specs for each layer", "= self.pool4(batch) batch = func.rrelu(self.conv7_normed(self.conv7(batch))) batch = func.rrelu(self.conv8_normed(self.conv8(batch))) # Pass", "output of the network \"\"\" # Apply first convolution, followed", "marked #TODO. ################################################################################ # PyTorch and neural network imports import", "10 output channels, [6x6] kernel, initialization: xavier self.conv4 = nn.Conv2d(in_channels=16,", "the provided specs for each layer #TODO: conv2: 4 input", "what should out_features be? self.out_features = 14 def forward(self, batch):", "'batch' #batch = func.sigmoid(batch) return batch def num_flat_features(self, inputs): #", "this function *needs* to be called \"forward\" for PyTorch to", "- logits: (Variable) The output of the network \"\"\" #", "conv1 self.conv1_normed = nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal", "PyTorch and neural network imports import torch from torch.autograd import", "batch = self.pool5(batch) # Reshape the output of the conv3", "plt import numpy as np import os class Arch2CNN(nn.Module): \"\"\"", "\"forward\" for PyTorch to automagically perform the forward pass. Params:", "func.rrelu(self.conv1_normed(self.conv1(batch))) batch = self.pool1(batch) # Apply conv2 and conv3 similarly", "of images through each layer of the network, applying non-linearities", "the forward pass. Params: ------- - batch: (Tensor) An input", "nn.BatchNorm2d(4) # Initialized weights using the Xavier-Normal method torch_init.xavier_normal_(self.conv1.weight) self.pool1", "in the areas marked #TODO. ################################################################################ # PyTorch and neural", "= nn.Linear(in_features=512, out_features=128) self.fc2_normed = nn.BatchNorm1d(128) torch_init.xavier_normal_(self.fc2.weight) #TODO: fc3 self.fc3", "rest (why?) batch = self.fc3(batch) # Return the class predictions", "conv3 to the pooling layer batch = self.pool5(batch) # Reshape", "to pass to fully-connected layer batch = batch.view(-1, self.num_flat_features(batch)) #", "convolution, followed by ReLU non-linearity; # use batch-normalization on its", "the inputs size = inputs.size()[1:] # Track the number of" ]
[ "import credentials from datetime import datetime, timedelta class NewsAPI: def", "except: raise RuntimeError('Failed to retrive New York Times data.') if", "def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week", "= urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive", "last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url =", "= 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key='", "articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise", "articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5:", "urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New", "if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles", "if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles >", "'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4],", "+ '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles =", "= today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q='", "timedelta(weeks = 1) last_week = today - delta begin_date =", "data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles", "- delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic", "York Times data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length()", "1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d') url", "- 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New", "5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits']", "topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try:", "class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self,", "else: raise RuntimeError('Failed to find any New York Times articles", "'&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url =", "nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta =", "articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New York Times", "__init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta", "topic, today): delta = timedelta(weeks = 1) last_week = today", "RuntimeError('Failed to retrive New York Times data.') if articles['status'] !=", "json import urllib.request import credentials from datetime import datetime, timedelta", "delta = timedelta(weeks = 1) last_week = today - delta", "New York Times data.') if articles['status'] != 'OK': num_of_articles =", "datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api", "!= 'OK': num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return", "last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date", "= timedelta(weeks = 1) last_week = today - delta begin_date", "nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1)", "Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj = datetime.now()", "articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return", "num_of_articles = articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits']", "raise RuntimeError('Failed to find any New York Times articles with", "York Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj =", "from datetime import datetime, timedelta class NewsAPI: def __init__(self, nyt_api):", "NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic,", "'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' +", "return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else:", "with query.') api = NewsAPI(credentials.NYT_API) date_time_obj = datetime.now() api.get_nyt_last_week_articles('election', date_time_obj)", "import urllib.request import credentials from datetime import datetime, timedelta class", "delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic +", "'&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read())", "= articles['response']['docs'].length() if num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else:", "raise RuntimeError('Failed to retrive New York Times data.') if articles['status']", "return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find", "articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj = datetime.now() api.get_nyt_last_week_articles('election',", "= last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' +", "import datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access =", "begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date='", "import json import urllib.request import credentials from datetime import datetime,", "find any New York Times articles with query.') api =", "+ topic + '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access", "= nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks =", "articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any", "+ begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url)", "= 1) last_week = today - delta begin_date = last_week.strftime('%Y%m%d')", "1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to find any New York", "to retrive New York Times data.') if articles['status'] != 'OK':", "self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise", "def __init__(self, nyt_api): self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today):", "RuntimeError('Failed to find any New York Times articles with query.')", "json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to", "datetime import datetime, timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access", "try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except: raise RuntimeError('Failed", "to find any New York Times articles with query.') api", "else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed to", "credentials from datetime import datetime, timedelta class NewsAPI: def __init__(self,", "self.nyt_access = nyt_api def get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks", "New York Times articles with query.') api = NewsAPI(credentials.NYT_API) date_time_obj", "json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times data.')", "urllib.request import credentials from datetime import datetime, timedelta class NewsAPI:", "today): delta = timedelta(weeks = 1) last_week = today -", "+ '&begin_date=' + begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url", "articles = json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York", "+ self.nyt_access try: json_url = urllib.request.urlopen(url) articles = json.loads(json_url.read()) except:", "get_nyt_last_week_articles(self, topic, today): delta = timedelta(weeks = 1) last_week =", "begin_date + '&sort=best&type_of_material=Article&api-key=' + self.nyt_access try: json_url = urllib.request.urlopen(url) articles", "timedelta class NewsAPI: def __init__(self, nyt_api): self.nyt_access = nyt_api def", "retrive New York Times data.') if articles['status'] != 'OK': num_of_articles", "num_of_articles > 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles -", "Times data.') if articles['status'] != 'OK': num_of_articles = articles['response']['docs'].length() if", "any New York Times articles with query.') api = NewsAPI(credentials.NYT_API)", "> 5: return articles['response']['docs'][0:4], articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1],", "articles['response']['meta']['hits'] else: return articles['response']['docs'][0:num_of_articles - 1], articles['response']['meta']['hits'] else: raise RuntimeError('Failed", "today - delta begin_date = last_week.strftime('%Y%m%d') url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' +", "url = 'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + topic + '&begin_date=' + begin_date +", "= json.loads(json_url.read()) except: raise RuntimeError('Failed to retrive New York Times" ]
[ "str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" +", "api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} ==", "source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) +", "assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [", "the License. from smexperiments import trial_component, api_types import datetime import", "the License. A copy of # the License is located", "datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\"", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time", "{ \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\":", "list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected", "+ str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i),", "assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"),", "for the specific # language governing permissions and limitations under", "unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls", "assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []}", "# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights", ") ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time", "obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\")", "obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\",", "def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc)", "= trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\")", "{\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before =", "CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls ==", "trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\",", "{}, } for i in range(10, 20) ] }, ]", "end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3)", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect", "= \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value =", "+ datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for", "[ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0,", "+ datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc)", "test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore() == [\"ResponseMetadata\",", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ {", "language governing permissions and limitations under the License. from smexperiments", "ANY KIND, either express or implied. See the License for", "last_modified_by={}, ) for i in range(20) ] result = list(", "range(10, 20) ] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\"", "2.0 (the \"License\"). You # may not use this file", "status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i),", "] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time =", "the \"license\" file accompanying this file. This file is #", "governing permissions and limitations under the License. from smexperiments import", "{\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\":", "sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert", "= list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert", "api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now )", "A copy of # the License is located at #", "\"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0},", "\"LastModifiedBy\": {}, } for i in range(10) ], \"NextToken\": \"100\",", "end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={},", "def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\",", "assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\",", "\"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\":", "Reserved. # # Licensed under the Apache License, Version 2.0", "test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def", "experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls", "trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj", "[ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i),", "creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i", "= { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\",", "in range(10, 20) ] }, ] expected = [ api_types.TrialComponentSummary(", "3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], }", "datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) +", "License is located at # # http://aws.amazon.com/apache2.0/ # # or", "datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for", "trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected ==", "Amazon.com, Inc. or its affiliates. All Rights Reserved. # #", "} obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn", "= {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\",", "return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", }", "ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert", "list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\",", "\"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\":", ") assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\",", "expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i),", "} for i in range(10) ], \"NextToken\": \"100\", }, {", "SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls ==", "\"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\")", "assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"}", "== obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0,", "file. This file is # distributed on an \"AS IS\"", "= { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\":", ") expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\",", "specific # language governing permissions and limitations under the License.", "Inc. or its affiliates. All Rights Reserved. # # Licensed", "= [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i),", "{\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\",", "now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\",", "obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore() == [\"ResponseMetadata\", \"CreatedBy\"]", "import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value", "def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0, 0)", "obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\")", "created_before = datetime.datetime(1999, 10, 12, 0, 0, 0) created_after =", "sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result", "\"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time +", "DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value =", "source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result expected_calls", "file except in compliance with the License. A copy of", "\"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1,", "obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert", "\"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value =", "], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\"", "sort_order=\"Ascending\", ) ) assert expected == result expected_calls = [", "{} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\",", "SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value", "def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj =", "obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert", "[]} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999,", "expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\")", "+ datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10, 20)", "is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND,", "next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert", "# ANY KIND, either express or implied. See the License", "the License for the specific # language governing permissions and", "== obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")}", "datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\":", "sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj =", "{} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before,", "created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls =", "= [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ]", "{\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\",", "+ datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\":", "import trial_component, api_types import datetime import pytest import unittest.mock @pytest.fixture", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time", "assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value", "sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\",", "# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i),", "start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2)", "{\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\":", "\"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\":", "sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", )", "start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time", "0, 0) created_after = datetime.datetime(1990, 10, 12, 0, 0, 0)", "sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name", "+ str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i),", "\"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {}", "2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, }", "All Rights Reserved. # # Licensed under the Apache License,", "CONDITIONS OF # ANY KIND, either express or implied. See", "# language governing permissions and limitations under the License. from", "== list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0,", "== result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\",", "\"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99", "= {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client,", "\"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" +", "last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10)", "i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [", "12, 0, 0, 0) created_after = datetime.datetime(1990, 10, 12, 0,", "\"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\",", ") ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj =", "assert \"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\"", "not use this file except in compliance with the License.", "display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj =", "] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", )", "== obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now =", "\"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" +", "assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert", "\"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ],", "sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name", ") ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after,", "] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client,", "\"A\" == obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" ==", "file accompanying this file. This file is # distributed on", "2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #", "creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, }", "WARRANTIES OR CONDITIONS OF # ANY KIND, either express or", "under the License. from smexperiments import trial_component, api_types import datetime", "\"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time", "obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def", "== obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert", "0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\"", "max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list(", "\"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i),", "], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" ==", "str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time +", "obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc)", "display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj", "# Licensed under the Apache License, Version 2.0 (the \"License\").", "expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\",", "test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\":", "[ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" +", "this file except in compliance with the License. A copy", "source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i),", "{ \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\":", "= [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\",", "sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value =", "] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i),", "with the License. A copy of # the License is", "unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj", "\"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\":", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either", "datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i),", "{\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\":", "] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" +", "def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {}", "assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0,", "\"License\"). You # may not use this file except in", "Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.", "is located at # # http://aws.amazon.com/apache2.0/ # # or in", "License, Version 2.0 (the \"License\"). You # may not use", "creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4)", "def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {}", "or its affiliates. All Rights Reserved. # # Licensed under", "obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert", "unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def", "+ datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in", "[ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\":", "0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token =", "sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value", "= datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name = \"foo-trial\"", "count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def", "4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj =", "str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i),", "datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20)", "KIND, either express or implied. See the License for the", "License for the specific # language governing permissions and limitations", "+ str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\"", "20) ] }, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" +", "datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ {", "+ datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i),", "unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, )", "datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) +", "copy of # the License is located at # #", "{\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\":", "+ str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time", "\"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client): now", "sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client):", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status", "for i in range(10, 20) ] }, ] expected =", "= trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\"", "datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10) ], \"NextToken\":", "next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call(", "Apache License, Version 2.0 (the \"License\"). You # may not", "the specific # language governing permissions and limitations under the", "sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) assert expected == result expected_calls =", "License. A copy of # the License is located at", "TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ]", "sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\":", "for i in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client,", "smexperiments import trial_component, api_types import datetime import pytest import unittest.mock", "(the \"License\"). You # may not use this file except", "sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before,", "1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert", "+ datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i),", "import datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return", "use this file except in compliance with the License. A", "{ \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\",", "api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0,", "permissions and limitations under the License. from smexperiments import trial_component,", "+ str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time +", "http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying this", "+ str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\":", "SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls", "\"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {},", "implied. See the License for the specific # language governing", "\"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [", "\"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in", "10, 12, 0, 0, 0) created_after = datetime.datetime(1990, 10, 12,", "may not use this file except in compliance with the", "this file. This file is # distributed on an \"AS", "== sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value", "the License is located at # # http://aws.amazon.com/apache2.0/ # #", "\"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ { \"MetricName\":", "+ str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i),", "== obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") ==", "\"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\",", "= [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\"", "{ \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client", "\"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\":", "\"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\")", "end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time +", "WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express", "datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10, 20) ]", "sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\",", "\"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj", "sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\"", "sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name,", "import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def", "# # Licensed under the Apache License, Version 2.0 (the", "== obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn", "obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\":", "}, { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\":", "i in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\",", "= 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list(", "result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\", ) )", "assert \"bar\" == obj.display_name assert \"bazz\" == obj.trial_component_arn def test_load(sagemaker_boto_client):", "SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def", "= {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before", "experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value", "obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\":", "now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert", "= \"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert []", "# # http://aws.amazon.com/apache2.0/ # # or in the \"license\" file", "str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\":", "\"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\":", "\"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}},", "== sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert []", "\"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\":", "\"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\":", "# # or in the \"license\" file accompanying this file.", "test_save(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save()", "accompanying this file. This file is # distributed on an", "\"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time", "= trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\"", "+ str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\":", "== obj.trial_component_arn assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name", "Rights Reserved. # # Licensed under the Apache License, Version", "assert \"B\" == obj.trial_component_name assert \"C\" == obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\",", "either express or implied. See the License for the specific", "+ datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc)", "Version 2.0 (the \"License\"). You # may not use this", "NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client):", "MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_save(sagemaker_boto_client): obj", "assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\"", "\"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\":", "start_time + datetime.timedelta(hours=i), \"EndTime\": end_time + datetime.timedelta(hours=i), \"CreationTime\": creation_time +", "\"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\",", "\"license\" file accompanying this file. This file is # distributed", "message=\"D\") == obj.status assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters", "from smexperiments import trial_component, api_types import datetime import pytest import", "std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc)", "= {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name,", "SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls", "file is # distributed on an \"AS IS\" BASIS, WITHOUT", "\"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert \"bazz\" ==", "{\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary(", "This file is # distributed on an \"AS IS\" BASIS,", "\"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time +", "sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client,", "expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert", "\"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\":", "\"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\": {\"E\":", "= trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def", "{\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i),", "avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time =", "metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ]", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ {", "Licensed under the Apache License, Version 2.0 (the \"License\"). You", "trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF #", ") sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" ==", "datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ] result =", "trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore():", "last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10,", "+ str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time", "trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert \"B\" ==", "of # the License is located at # # http://aws.amazon.com/apache2.0/", "max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\",", "# the License is located at # # http://aws.amazon.com/apache2.0/ #", "and limitations under the License. from smexperiments import trial_component, api_types", "\"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\":", "1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\":", "message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time", "trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" ==", "\"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0,", "str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" + str(i), \"Status\":", "media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0,", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect =", "99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client,", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=3) last_modified_time =", "test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) +", "{} obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\")", "\"LastModifiedBy\": {}, } for i in range(10, 20) ] },", "def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\":", "\"K\", \"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client)", "in the \"license\" file accompanying this file. This file is", "[] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12,", "\"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\"", "at # # http://aws.amazon.com/apache2.0/ # # or in the \"license\"", "def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore() ==", "test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create(", "in compliance with the License. A copy of # the", "+ datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ] result", "1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}},", "} ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\"", "0, 0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token", "expected_calls = [ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\",", "list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0,", "= \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results =", "<gh_stars>0 # Copyright 2019 Amazon.com, Inc. or its affiliates. All", "+ datetime.timedelta(hours=3) last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [", "trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def", "0) created_after = datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name", "{\"StringValue\": \"G\"}}, \"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\":", "obj = trial_component.TrialComponent.load(trial_component_name=\"foo\", sagemaker_boto_client=sagemaker_boto_client) sagemaker_boto_client.describe_trial_component.assert_called_with(TrialComponentName=\"foo\") assert \"A\" == obj.trial_component_arn assert", "under the Apache License, Version 2.0 (the \"License\"). You #", "\"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0,", "{ \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\"", "+ datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, )", "datetime.timedelta(hours=i), \"CreationTime\": creation_time + datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\":", "datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock()", "\"J\", \"Count\": 1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\":", "10, 12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name =", "} obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\")", "{}, } for i in range(10) ], \"NextToken\": \"100\", },", "\"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\": [ {", "api_types import datetime import pytest import unittest.mock @pytest.fixture def sagemaker_boto_client():", "sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = { \"TrialComponentArn\": \"bazz\",", "[] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token,", "last_modified_time=last_modified_time + datetime.timedelta(hours=i), last_modified_by={}, ) for i in range(20) ]", "trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\",", "= datetime.datetime(1999, 10, 12, 0, 0, 0) created_after = datetime.datetime(1990,", "\"InputArtifacts\": {\"H\": {\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\",", "unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value =", "# http://aws.amazon.com/apache2.0/ # # or in the \"license\" file accompanying", "assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\",", "See the License for the specific # language governing permissions", "+ datetime.timedelta(hours=i), end_time=end_time + datetime.timedelta(hours=i), creation_time=creation_time + datetime.timedelta(hours=i), last_modified_time=last_modified_time +", ") for i in range(20) ] result = list( trial_component.TrialComponent.list(", "api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\",", "SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client):", "datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name", "# or in the \"license\" file accompanying this file. This", "display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client ) sagemaker_boto_client.create_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert", "trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\"", "\"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" +", "trial_name = \"foo-trial\" experiment_name = \"foo-experiment\" next_token = \"<PASSWORD>\" max_results", "0, 0, 0) created_after = datetime.datetime(1990, 10, 12, 0, 0,", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY", "[ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), ] assert", "except in compliance with the License. A copy of #", "max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client): start_time", "CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99, ) ] assert expected_calls", "\"SourceArn\": \"K\", \"Timestamp\": now, } ], } obj = trial_component.TrialComponent.load(trial_component_name=\"foo\",", "obj.delete() sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert", "\"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}}, \"Metrics\":", "datetime.datetime(1999, 10, 12, 0, 0, 0) created_after = datetime.datetime(1990, 10,", "\"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\":", "{\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\", media_type=\"text/plain\")}", "trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.update_trial_component.return_value = {} obj.save() sagemaker_boto_client.update_trial_component.assert_called_with(TrialComponentName=\"foo\", DisplayName=\"bar\") def test_delete(sagemaker_boto_client):", "\"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\",", "str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)}, \"StartTime\": start_time", "\"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"}, \"Parameters\":", "or in the \"license\" file accompanying this file. This file", "\"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" + str(i), \"TrialComponentArn\": \"B\" +", "} for i in range(10, 20) ] }, ] expected", "pytest import unittest.mock @pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client):", "DisplayName=\"bar\") assert \"foo\" == obj.trial_component_name assert \"bar\" == obj.display_name assert", "datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\",", "{\"Value\": \"s3://foo/bar\", \"MediaType\": \"text/plain\"}}, \"OutputArtifacts\": {\"I\": {\"Value\": \"s3://whizz/bang\", \"MediaType\": \"text/plain\"}},", "test_delete(sagemaker_boto_client): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") sagemaker_boto_client.delete_trial_component.return_value = {} obj.delete()", "OF # ANY KIND, either express or implied. See the", "created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) ) expected_calls = [", "timestamp=now ) ] def test_list(sagemaker_boto_client): start_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)", "datetime.timedelta(hours=i), \"LastModifiedTime\": last_modified_time + datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i", "+ str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i), source_arn=\"D\" +", "trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results, sort_by=\"CreationTime\", sort_order=\"Ascending\", ) )", "limitations under the License. from smexperiments import trial_component, api_types import", "== obj.trial_component_arn def test_load(sagemaker_boto_client): now = datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = {", "[ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now", "\"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\": \"K\", \"Timestamp\": now,", "\"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\"", "for i in range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\":", "assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client)) def test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10,", "str(i), \"TrialComponentArn\": \"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\":", "obj.display_name assert api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"D\") == obj.status assert {\"E\": 1.0, \"F\":", "expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"),", "express or implied. See the License for the specific #", "= datetime.datetime.now(datetime.timezone.utc) sagemaker_boto_client.describe_trial_component.return_value = { \"TrialComponentArn\": \"A\", \"TrialComponentName\": \"B\", \"DisplayName\":", "\"A\", \"TrialComponentName\": \"B\", \"DisplayName\": \"C\", \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"D\"},", "sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] ==", "@pytest.fixture def sagemaker_boto_client(): return unittest.mock.Mock() def test_create(sagemaker_boto_client): sagemaker_boto_client.create_trial_component.return_value = {", "its affiliates. All Rights Reserved. # # Licensed under the", "\"B\" + str(i), \"DisplayName\": \"C\" + str(i), \"SourceArn\": \"D\" +", "\"<PASSWORD>\" max_results = 99 sagemaker_boto_client.list_trial_components.return_value = {} assert [] ==", ") ) assert expected == result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\",", "# may not use this file except in compliance with", "str(i), \"SourceArn\": \"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\"", "or implied. See the License for the specific # language", "str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)), start_time=start_time + datetime.timedelta(hours=i), end_time=end_time +", "12, 0, 0, 0) trial_name = \"foo-trial\" experiment_name = \"foo-experiment\"", "{\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1, min=1.0, max=2.0,", "api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\" + str(i), display_name=\"C\" + str(i),", "result expected_calls = [ unittest.mock.call(SortBy=\"CreationTime\", SortOrder=\"Ascending\", SourceArn=\"foo\"), unittest.mock.call(NextToken=\"100\", SortBy=\"CreationTime\", SortOrder=\"Ascending\",", "}, ] expected = [ api_types.TrialComponentSummary( trial_component_name=\"A\" + str(i), trial_component_arn=\"B\"", "\"D\" + str(i), \"Status\": {\"PrimaryStatus\": \"InProgress\", \"Message\": \"E\" + str(i)},", "range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\", sort_order=\"Ascending\",", "datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) end_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=2) creation_time =", "You # may not use this file except in compliance", "compliance with the License. A copy of # the License", "+ datetime.timedelta(hours=i), \"LastModifiedBy\": {}, } for i in range(10) ],", "display_name=\"C\" + str(i), source_arn=\"D\" + str(i), status=api_types.TrialComponentStatus(primary_status=\"InProgress\", message=\"E\" + str(i)),", "] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\":", "min=1.0, max=2.0, avg=3.0, std_dev=4.0, source_arn=\"K\", timestamp=now ) ] def test_list(sagemaker_boto_client):", "in range(20) ] result = list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, source_arn=\"foo\", sort_by=\"CreationTime\",", "SourceArn=\"foo\"), ] assert expected_calls == sagemaker_boto_client.list_trial_components.mock_calls def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value =", "i in range(10, 20) ] }, ] expected = [", "assert [] == list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after,", "\"TrialComponentArn\": \"bazz\", } obj = trial_component.TrialComponent.create( trial_component_name=\"foo\", display_name=\"bar\", sagemaker_boto_client=sagemaker_boto_client )", "sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [ { \"TrialComponentName\": \"A\" +", "located at # # http://aws.amazon.com/apache2.0/ # # or in the", "range(10) ], \"NextToken\": \"100\", }, { \"TrialComponentSummaries\": [ { \"TrialComponentName\":", "\"text/plain\"}}, \"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0,", "sagemaker_boto_client.delete_trial_component.assert_called_with(TrialComponentName=\"foo\") def test_boto_ignore(): obj = trial_component.TrialComponent(sagemaker_boto_client, trial_component_name=\"foo\", display_name=\"bar\") assert obj._boto_ignore()", "affiliates. All Rights Reserved. # # Licensed under the Apache", "media_type=\"text/plain\")} assert {\"I\": api_types.TrialComponentArtifact(value=\"s3://whizz/bang\", media_type=\"text/plain\")} assert [ api_types.TrialComponentMetricSummary( metric_name=\"J\", count=1,", "trial_component, api_types import datetime import pytest import unittest.mock @pytest.fixture def", "last_modified_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\":", "the Apache License, Version 2.0 (the \"License\"). You # may", "\"Message\": \"D\"}, \"Parameters\": {\"E\": {\"NumberValue\": 1.0}, \"F\": {\"StringValue\": \"G\"}}, \"InputArtifacts\":", "= datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4) sagemaker_boto_client.list_trial_components.side_effect = [ { \"TrialComponentSummaries\": [", "def test_list_empty(sagemaker_boto_client): sagemaker_boto_client.list_trial_components.return_value = {\"TrialComponentSummaries\": []} assert [] == list(trial_component.TrialComponent.list(sagemaker_boto_client=sagemaker_boto_client))", "test_list_trial_components_call_args(sagemaker_boto_client): created_before = datetime.datetime(1999, 10, 12, 0, 0, 0) created_after", "created_after = datetime.datetime(1990, 10, 12, 0, 0, 0) trial_name =", "License. from smexperiments import trial_component, api_types import datetime import pytest", "== list( trial_component.TrialComponent.list( sagemaker_boto_client=sagemaker_boto_client, trial_name=trial_name, experiment_name=experiment_name, created_before=created_before, created_after=created_after, next_token=next_token, max_results=max_results,", "\"Message\": \"E\" + str(i)}, \"StartTime\": start_time + datetime.timedelta(hours=i), \"EndTime\": end_time", "\"Metrics\": [ { \"MetricName\": \"J\", \"Count\": 1, \"Min\": 1.0, \"Max\":", "1, \"Min\": 1.0, \"Max\": 2.0, \"Avg\": 3.0, \"StdDev\": 4.0, \"SourceArn\":", "assert {\"E\": 1.0, \"F\": \"G\"} == obj.parameters assert {\"H\": api_types.TrialComponentArtifact(value=\"s3://foo/bar\",", "[ unittest.mock.call( TrialName=\"foo-trial\", ExperimentName=\"foo-experiment\", CreatedBefore=created_before, CreatedAfter=created_after, SortBy=\"CreationTime\", SortOrder=\"Ascending\", NextToken=\"<PASSWORD>token\", MaxResults=99,", "OR CONDITIONS OF # ANY KIND, either express or implied." ]
[ "the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo:", "# emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover", "oligo to the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand():", "strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part =", "2. install the crossover 3. apply the strand5p oligo to", "3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "# end def def undo(self): part = self._part strand5p =", "to the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): #", "old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the", "restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the", "oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to", "olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the", "strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p", "self._update_oligo: # Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True)", "end of strand5p to the 5' end of strand3p this", "strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p #", "if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified oligo", "length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and apply", "self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part =", "strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p =", "the 5' oligo to the 3' strand new_olg3p.removeFromPart() for strand", "strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end", "4. apply the new strand3p oligo to the strand3p \"\"\"", "doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to restore whatever", "Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to", "end def def redo(self): part = self._part strand5p = self._strand5p", "strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet()", "# Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else:", "the old oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand():", "strand5p oligo to the strand3p \"\"\" def __init__(self, part, strand5p,", "oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits", "the crossover 3. apply the strand5p oligo to the strand3p", "Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if", "oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and", "part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p", "old oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): #", "strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand():", "preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo", "for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) #", "end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the", "def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part =", "uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else:", "= strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx =", "to the strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand,", "self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p", "strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def", "# 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: #", "self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 =", "old oligo of strand3p 2. install the crossover 3. update", "random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3'", "3. apply the old oligo to strand3p old_olg3p.addToPart(part) for strand", "self._new_oligo3p # 0. Deselect the involved strands doc = strand5p.document()", "self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end def def", "strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "# 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False)", "= strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end", "n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end", "strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p", "the 3' end of strand5p to the 5' end of", "1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the", "strand3p.oligo().isLoop() # end def def redo(self): part = self._part strand5p", "= prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for", "= ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p =", "undo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx", "%s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p)", "import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the", "= self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p =", "3. apply the old oligo to strand3p new_olg3p.addToPart(part) for strand", "= strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx =", "old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False)", "strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part =", "Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) #", "a Xover from the 3' end of strand5p to the", "doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need to restore", "else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2.", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end", "strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None)", "doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if olg5p ==", "strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length())", "self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p =", "= strand3p.oligo().isLoop() # end def def redo(self): part = self._part", "strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() #", "__init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part", "Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name))", "\"\"\" Creates a Xover from the 3' end of strand5p", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p", "st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if", "emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3. install", "3. update the oligo length 4. apply the new strand3p", "prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from", "oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and", "strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if", "import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates", "part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p", "n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def redo(self): part", "Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2.", "Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the", "cadnano.strand import Strand from cadnano import getBatch import cadnano.preferences as", "strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part", "= self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p =", "self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2.", "the crossover 3. update the oligo length 4. apply the", "= self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p =", "# strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self):", "self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p", "redo(self): part = self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx", "as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover", "self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class", "emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p)", "restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the", "strand3p.oligo() self._update_oligo = update_oligo # end def def redo(self): part", "xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime()", "from the 3' end of strand5p to the 5' end", "self).__init__(\"create xover\") self._part = part self._strand5p = strand5p self._strand5p_idx =", "install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p =", "self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo()", "else: # 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) #", "2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply", "= self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p =", "strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class RemoveXoverCommand(UndoCommand): \"\"\"", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p", "ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) #", "part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def", "\\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength())", "strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the involved strands", "strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 =", "from cadnano.cnproxy import UndoCommand from cadnano.strand import Strand from cadnano", "= self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p =", "= strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS", "strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p", "\"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand,", "__init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\")", "= self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0.", "old oligo and apply the 5' oligo to the 3'", "st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p)", "restore whatever the old Oligo._strand5p was else: # 1. update", "end else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5", "strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() #", "strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test", "# emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3.", "# 0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p)", "Strand from cadnano import getBatch import cadnano.preferences as prefs import", "self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect", "install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p =", "involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall", "# end def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes", "self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else", "self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo", "strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else", "class CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3' end", "the oligo length 4. apply the new strand3p oligo to", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the", "# 3. apply the old oligo to strand3p new_olg3p.addToPart(part) for", "doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if", "the 3' strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits", "the new strand3p oligo to the strand3p \"\"\" def __init__(self,", "was else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) #", "length 4. apply the new strand3p oligo to the strand3p", "preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo", "olg5p) # end else # 3. install the Xover strand5p.setConnection3p(strand3p)", "strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "apply the 5' oligo to the 3' strand old_olg3p.removeFromPart() for", "Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified", "the strand5p oligo to the strand3p \"\"\" def __init__(self, part,", "the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1.", "apply the new strand3p oligo to the strand3p \"\"\" def", "self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect", "olg5p.setLoop(True) else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) #", "if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class", "strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo", "RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3' end of", "import getBatch import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand):", "self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p", "in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop()", "n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def", "0. Deselect the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p)", "the old oligo and apply the 5' oligo to the", "new_olg3p = self._new_oligo3p # 0. Deselect the involved strands doc", "of strand3p 2. install the crossover 3. apply the strand5p", "strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p)", "strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p =", "prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end", "need to restore whatever the old Oligo._strand5p was else: #", "Strand.setOligo(strand, olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p", "= strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No need", "from cadnano.strand import Strand from cadnano import getBatch import cadnano.preferences", "crossover 3. apply the strand5p oligo to the strand3p \"\"\"", "= strand3p.oligo() self._update_oligo = update_oligo # end def def redo(self):", "strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx", "self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx", "import UndoCommand from cadnano.strand import Strand from cadnano import getBatch", "else: # 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) #", "strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop =", "# end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def", "the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name,", "\"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part", "prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand", "self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the involved strands", "super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p self._strand5p_idx", "part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part", "Creates a Xover from the 3' end of strand5p to", "olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo length", "update_oligo=True): super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p = strand5p", "def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover", "self).__init__(\"remove xover\") self._part = part self._strand5p = strand5p self._strand5p_idx =", "old Oligo._strand5p was else: # 1. update preserved oligo length", "the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if", "olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to strand3p old_olg3p.addToPart(part)", "5' oligo to the 3' strand new_olg3p.removeFromPart() for strand in", "strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part", "\"\"\" Removes a Xover from the 3' end of strand5p", "== strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo length", "doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness if olg5p", "strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) #", "strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p = self._old_oligo3p #", "self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p", "Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p =", "if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part", "# 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3.", "= self._strand3p_idx olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0.", "= %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p", "ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p)", "old_olg3p.setLoop(False) else: # 2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length())", "oligo and apply the 5' oligo to the 3' strand", "%s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p =", "strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 =", "self._isLoop = strand3p.oligo().isLoop() # end def def redo(self): part =", "= strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS", "old oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): #", "olg5p = strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the", "self._update_oligo = update_oligo # end def def redo(self): part =", "def redo(self): part = self._part strand5p = self._strand5p strand5p_idx =", "class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3' end", "the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "apply the old oligo to strand3p new_olg3p.addToPart(part) for strand in", "Oligo._strand5p was else: # 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length())", "strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx", "not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p", "strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the", "strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList", "strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo # end def", "# 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s,", "= strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy()", "emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "else: # 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2.", "the strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove", "oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand3p):", "self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo = update_oligo #", "1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p)", "st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p", "self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo()", "strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if", "the 5' oligo to the 3' strand old_olg3p.removeFromPart() for strand", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3. install", "= part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p =", "# strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch(): if", "Removes a Xover from the 3' end of strand5p to", "doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True) # No", "import Strand from cadnano import getBatch import cadnano.preferences as prefs", "doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for", "= %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "Test for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: #", "# 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3.", "1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p", "of strand3p 2. install the crossover 3. update the oligo", "length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to strand3p", "vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p", "Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update", "strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document()", "strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "end of strand3p this needs to 1. preserve the old", "update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old", "needs to 1. preserve the old oligo of strand3p 2.", "strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p) self._isLoop", "= ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) #", "ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType()", "= self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0.", "colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0)", "class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from the 3'", "= part self._strand5p = strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p =", "old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p)", "= self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p =", "Remove the old oligo and apply the 5' oligo to", "No need to restore whatever the old Oligo._strand5p was else:", "self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect", "= ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p)", "= self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p =", "apply the 5' oligo to the 3' strand new_olg3p.removeFromPart() for", "old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore the modified oligo length", "if self._update_oligo: # Test for Loopiness if olg5p == strand3p.oligo():", "for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5", "cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\" Creates a", "vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch():", "ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3", "part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) #", "new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType()", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet()", "vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p,", "self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx", "olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved oligo", "strand new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "new strand3p oligo to the strand3p \"\"\" def __init__(self, part,", "olg5p = strand5p.oligo() # 0. Deselect the involved strands doc", "= ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p)", "update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old", "install the crossover 3. apply the strand5p oligo to the", "cadnano import getBatch import cadnano.preferences as prefs import random class", "xover\") self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p_idx", "the involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop:", "strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo()", "olg5p.incrementLength(new_olg3p.length()) # 2. Remove the old oligo and apply the", "vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def #", "strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p", "old_olg3p = self._old_oligo3p # 0. Deselect the involved strands doc", "part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\") self._part = part self._strand5p", "apply the old oligo to strand3p old_olg3p.addToPart(part) for strand in", "def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def redo(self):", "# strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def", "= update_oligo # end def def redo(self): part = self._part", "self._isLoop: olg5p.setLoop(True) # No need to restore whatever the old", "if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) #", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p", "= strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: # Test for Loopiness", "olg5p) # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p =", "strand3p 2. install the crossover 3. apply the strand5p oligo", "# end def def redo(self): part = self._part strand5p =", "strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part strand5p", "modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo", "new_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p)", "3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p", "n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple()", "= strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the involved", "# 3. apply the old oligo to strand3p old_olg3p.addToPart(part) for", "self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p", "doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo:", "1. preserve the old oligo of strand3p 2. install the", "self._strand5p.oligo() # 0. Deselect the involved strands doc = strand5p.document()", "strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore", "3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: #", "to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the involved strands", "and apply the 5' oligo to the 3' strand new_olg3p.removeFromPart()", "self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo", "olg5p.setLoop(True) # No need to restore whatever the old Oligo._strand5p", "self._strand3p_idx = strand3p.idx5Prime() n_o3p = self._new_oligo3p = strand3p.oligo().shallowCopy() colorList =", "= self._old_oligo3p olg5p = strand5p.oligo() # 0. Deselect the involved", "= self._new_oligo3p # 0. Deselect the involved strands doc =", "length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to strand3p", "= strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None)", "strand3p 2. install the crossover 3. update the oligo length", "if self._isLoop: olg5p.setLoop(False) olg5p.setStrand5p(strand3p) else: # 2. restore the modified", "= strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p)", "super(CreateXoverCommand, self).__init__(\"create xover\") self._part = part self._strand5p = strand5p self._strand5p_idx", "if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in", "end def def undo(self): part = self._part strand5p = self._strand5p", "of strand5p to the 5' end of strand3p this needs", "= self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0.", "= self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx =", "st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo:", "self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect", "oligo of strand3p 2. install the crossover 3. apply the", "end def # end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a", "self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p", "strand3p oligo to the strand3p \"\"\" def __init__(self, part, strand5p,", "strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand,", "5' oligo to the 3' strand old_olg3p.removeFromPart() for strand in", "# No need to restore whatever the old Oligo._strand5p was", "3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p", "strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() #", "to 1. preserve the old oligo of strand3p 2. install", "3. apply the strand5p oligo to the strand3p \"\"\" def", "strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def #", "# emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet() vh5p =", "strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\ else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name())", "oligo length 4. apply the new strand3p oligo to the", "olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply the", "def def undo(self): part = self._part strand5p = self._strand5p strand5p_idx", "strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx old_olg3p", "strand3p \"\"\" def __init__(self, part, strand5p, strand3p): super(RemoveXoverCommand, self).__init__(\"remove xover\")", "strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else # 3. install the", "= self._new_oligo3p = strand3p.oligo().shallowCopy() colorList = prefs.STAP_COLORS if strand5p.strandSet().isStaple() \\", "= self._strand3p strand3p_idx = self._strand3p_idx olg5p = strand5p.oligo() old_olg3p =", "strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True):", "old oligo of strand3p 2. install the crossover 3. apply", "if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: #", "= strand5p.strandSet() vh5p = ss5.virtualHelix() st5p = ss5.strandType() ss3 =", "CreateXoverCommand(UndoCommand): \"\"\" Creates a Xover from the 3' end of", "part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not", "# end else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p)", "if self._isLoop: olg5p.setLoop(True) # No need to restore whatever the", "# 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet()", "ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p)", "install the crossover 3. update the oligo length 4. apply", "self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p", "# strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end", "vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end", "Strand.setOligo(strand, olg5p) # end else # 3. install the Xover", "strand3p this needs to 1. preserve the old oligo of", "self._old_oligo3p # 0. Deselect the involved strands doc = strand5p.document()", "else # 3. install the Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 =", "strand3p) # if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p)", "= strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime() n_o3p =", "the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old", "cadnano.cnproxy import UndoCommand from cadnano.strand import Strand from cadnano import", "= strand5p.oligo() # 0. Deselect the involved strands doc =", "self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p self._strand3p_idx", "for Loopiness if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1.", "the modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old", "strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "3' end of strand5p to the 5' end of strand3p", "to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal", "ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end", "this needs to 1. preserve the old oligo of strand3p", "2. restore the modified oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply", "getBatch import cadnano.preferences as prefs import random class CreateXoverCommand(UndoCommand): \"\"\"", "in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, old_olg3p) ss5 = strand5p.strandSet()", "strand5p_idx = self._strand5p_idx strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p", "# emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p =", "strand5p.oligo() old_olg3p = self._old_oligo3p # 0. Deselect the involved strands", "# 2. Remove the old oligo and apply the 5'", "the 5' end of strand3p this needs to 1. preserve", "length olg5p.incrementLength(old_olg3p.length()) # 2. Remove the old oligo and apply", "strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else:", "involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._isLoop: olg5p.setLoop(True)", "preserve the old oligo of strand3p 2. install the crossover", "= ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo", "part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p = strand3p", "= strand5p.oligo() new_olg3p = self._new_oligo3p # 0. Deselect the involved", "# end class class RemoveXoverCommand(UndoCommand): \"\"\" Removes a Xover from", "ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and", "the old oligo to strand3p new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand():", "= self._old_oligo3p # 0. Deselect the involved strands doc =", "the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): # emits", "to the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p,", "emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix()", "the old Oligo._strand5p was else: # 1. update preserved oligo", "olg5p = self._strand5p.oligo() # 0. Deselect the involved strands doc", "if olg5p == strand3p.oligo(): olg5p.setLoop(True) else: # 1. update preserved", "# if self._update_oligo and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p)", "end def n_o3p.setStrand5p(strand3p) self._isLoop = strand3p.oligo().isLoop() # end def def", "update the oligo length 4. apply the new strand3p oligo", "ss5.virtualHelix() st5p = ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix()", "oligo of strand3p 2. install the crossover 3. update the", "# 1. update preserved oligo length olg5p.incrementLength(old_olg3p.length()) # 2. Remove", "#print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5 = strand5p.strandSet()", "# 1. update preserved oligo length olg5p.incrementLength(new_olg3p.length()) # 2. Remove", "crossover 3. update the oligo length 4. apply the new", "new_olg3p = self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the", "UndoCommand from cadnano.strand import Strand from cadnano import getBatch import", "the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx,", "from cadnano import getBatch import cadnano.preferences as prefs import random", "strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # 3.", "oligo to strand3p old_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits", "Xover from the 3' end of strand5p to the 5'", "for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p) ss5", "doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._isLoop:", "doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) # 1. uninstall the Xover", "to restore whatever the old Oligo._strand5p was else: # 1.", "apply the strand5p oligo to the strand3p \"\"\" def __init__(self,", "= strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p = strand3p.oligo() self._update_oligo =", "oligo length olg5p.decrementLength(old_olg3p.length()) # 3. apply the old oligo to", "= strand5p_idx self._strand3p = strand3p self._strand3p_idx = strand3p_idx self._old_oligo3p =", "oligo to the strand3p \"\"\" def __init__(self, part, strand5p, strand5p_idx,", "strand5p self._strand5p_idx = strand5p.idx3Prime() self._strand3p = strand3p self._strand3p_idx = strand3p.idx5Prime()", "n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) # end def n_o3p.setStrand5p(strand3p)", "1. uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test", "olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo to strand3p new_olg3p.addToPart(part)", "modified oligo length olg5p.decrementLength(new_olg3p.length()) # 3. apply the old oligo", "strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, olg5p) # end else #", "else prefs.SCAF_COLORS n_o3p.setColor(random.choice(colorList).name()) n_o3p.setLength(0) for strand in strand3p.generator3pStrand(): n_o3p.incrementLength(strand.totalLength()) #", "= self._strand5p.oligo() # 0. Deselect the involved strands doc =", "strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class", "= self._new_oligo3p olg5p = self._strand5p.oligo() # 0. Deselect the involved", "def def redo(self): part = self._part strand5p = self._strand5p strand5p_idx", "ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part,", "2. install the crossover 3. update the oligo length 4.", "Xover strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) ss5 = strand5p.strandSet() vh5p = ss5.virtualHelix() st5p", "to the 5' end of strand3p this needs to 1.", "2. Remove the old oligo and apply the 5' oligo", "ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) # strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) if", "strand3p = self._strand3p strand3p_idx = self._strand3p_idx new_olg3p = self._new_oligo3p olg5p", "strand5p.setConnection3p(strand3p) strand3p.setConnection5p(strand5p) #print('strand5p = %s, connection3p = %s'%(strand5p._name, strand3p._name)) ss5", "uninstall the Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness", "5' end of strand3p this needs to 1. preserve the", "olg5p.setStrand5p(strand3p) else: # 2. restore the modified oligo length olg5p.decrementLength(new_olg3p.length())", "of strand3p this needs to 1. preserve the old oligo", "to the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand(): #", "def undo(self): part = self._part strand5p = self._strand5p strand5p_idx =", "self._strand3p strand3p_idx = self._strand3p_idx old_olg3p = self._old_oligo3p olg5p = strand5p.oligo()", "the old oligo of strand3p 2. install the crossover 3.", "strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self): part = self._part", "strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def # end class class RemoveXoverCommand(UndoCommand):", "strand5p to the 5' end of strand3p this needs to", "and not getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def", "whatever the old Oligo._strand5p was else: # 1. update preserved", "def __init__(self, part, strand5p, strand5p_idx, strand3p, strand3p_idx, update_oligo=True): super(CreateXoverCommand, self).__init__(\"create", "new_olg3p.addToPart(part) for strand in strand3p.generator3pStrand(): # emits strandHasNewOligoSignal Strand.setOligo(strand, new_olg3p)", "involved strands doc = strand5p.document() doc.removeStrandFromSelection(strand5p) doc.removeStrandFromSelection(strand3p) if self._update_oligo: #", "= ss5.strandType() ss3 = strand3p.strandSet() vh3p = ss3.virtualHelix() st3p =", "oligo to the 3' strand old_olg3p.removeFromPart() for strand in strand3p.generator3pStrand():", "getBatch(): if self._update_oligo: strand5p.strandUpdateSignal.emit(strand5p) strand3p.strandUpdateSignal.emit(strand3p) # end def def undo(self):", "update_oligo # end def def redo(self): part = self._part strand5p", "strand5p.strandXover5pChangedSignal.emit(strand5p, strand3p) # if self._update_oligo and not getBatch(): if self._update_oligo:", "# Test Loopiness if old_olg3p.isLoop(): old_olg3p.setLoop(False) else: # 2. restore", "self._part strand5p = self._strand5p strand5p_idx = self._strand5p_idx strand3p = self._strand3p", "self._part = part self._strand5p = strand5p self._strand5p_idx = strand5p_idx self._strand3p", "and apply the 5' oligo to the 3' strand old_olg3p.removeFromPart()", "strand3p.strandSet() vh3p = ss3.virtualHelix() st3p = ss3.strandType() part.partActiveVirtualHelixChangedSignal.emit(part, vh5p) #", "Xover strand5p.setConnection3p(None) strand3p.setConnection5p(None) if self._update_oligo: # Test Loopiness if old_olg3p.isLoop():" ]
[ "sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\" + sensor.id)", "temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\"", "temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\" + sensor.id) print(temperature_in_celsius)", "W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F)", "= sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor id:\" +", "sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN]) print(\"Sensor", "w1thermsensor import W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit", "from w1thermsensor import W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature()", "W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C,", "temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F,", "= sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN])", "sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units", "import W1ThermSensor sensor = W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit =", "= W1ThermSensor() temperature_in_celsius = sensor.get_temperature() temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F) temperature_in_all_units =" ]
[ "migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ]", "17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "'0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='',", "Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations = [", "on 2020-09-01 17:04 from django.db import migrations, models class Migration(migrations.Migration):", "dependencies = [ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField(", "3.1.1 on 2020-09-01 17:04 from django.db import migrations, models class", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tables',", "class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations =", "= [ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure',", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "Generated by Django 3.1.1 on 2020-09-01 17:04 from django.db import", "operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='', max_length=200), ),", "] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='', max_length=200),", "('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True,", "2020-09-01 17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'),", "by Django 3.1.1 on 2020-09-01 17:04 from django.db import migrations,", "Django 3.1.1 on 2020-09-01 17:04 from django.db import migrations, models", "# Generated by Django 3.1.1 on 2020-09-01 17:04 from django.db", "[ ('tables', '0003_exposure_category'), ] operations = [ migrations.AlterField( model_name='exposure', name='location',", "= [ migrations.AlterField( model_name='exposure', name='location', field=models.CharField(blank=True, default='', max_length=200), ), ]", "models class Migration(migrations.Migration): dependencies = [ ('tables', '0003_exposure_category'), ] operations" ]
[ "Europe Ltd. 2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py", "2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py __version__='3.3.0' __doc__='''Business", "#see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py __version__='3.3.0' __doc__='''Business charts'''", "ReportLab Europe Ltd. 2000-2016 #see license.txt for license details #history", "Ltd. 2000-2016 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py __version__='3.3.0'", "#Copyright ReportLab Europe Ltd. 2000-2016 #see license.txt for license details" ]
[ "= list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role", "check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as", "identities if x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'):", "= candidate_int - 2 # try the other way around", "required and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile:", "'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL',", "namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None)", "namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix')", "= compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info =", "gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos if", "if s.name.lower() == size), None) if size_info is None or", "= 'new' logger.debug(\"specified public IP '%s' not found. It will", "= [int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b,", "not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan:", "storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account", "'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None)", "not None and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count", "--assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import", "'is_default', None) is None: raise CLIError(\"usage error: '--role {}' is", "((1 << (32 - mask)) - 2) > int(vmss_instance_count *", "import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name):", "resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos", "SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import", "character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or", "result = next((s for s in vnet_match.subnets if _check_subnet(s)), None)", "= next((s for s in vnet_match.subnets if _check_subnet(s)), None) if", "forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden", "namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id", "or size_info.number_of_cores < 8: return # VMs need to be", "offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'),", "if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def", "'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2',", "'%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s'", "else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found. It", "namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd,", "error: --priority PRIORITY [--eviction-policy POLICY]') # endregion # region disk,", "'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the specific", "def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace)", "CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images from virtual", "StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did", "image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info", "return # 3 - create a new vnet/subnet namespace.vnet_type =", "gallery_image_name=res['child_name_1']) image_version_infos = [x for x in image_version_infos if not", "2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities:", "image.plan except CloudError as ex: logger.warning(\"Querying the image of '%s'", "'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks", "is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single", "'{}' is out of range of 2^16 subnet size'\" raise", "Linux, Debian \"Stretch\" with backports kernel # Oracle Linux 7.4,", "keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file names: #", "PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6", "'new' logger.debug(\"load balancer '%s' not found. It will be created.\",", "or [] from ._vm_utils import MSI_LOCAL_ID for i, _ in", "will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask)", "try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is", "safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file", "def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None:", ":return: resource group name or None :rtype: str \"\"\" from", "Linux 7.4, Windows Server 2016, Windows Server 2012R2 publisher, offer,", "StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus", "get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def", "continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing'", "CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri,", "namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load balancer will", "from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger =", "get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import", "Server 2016, Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher,", "if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing", "namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username", "profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk'", "applicable when assign system identity\") # keep 'identity_role' for output", "'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo',", "capable one. 'az vm list-skus' can be \" \"used to", "_get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address,", "empty\") is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern", "= urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]):", "None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3", "namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx,", "for Windows, ssh for Linux) by examining the OS type", "client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps =", "from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id =", "scale-sets\" elif namespace.instance_count > 100: err = \"'Standard' load balancer", "not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type", "in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There", "errors = [] try: loaded_secret = [validate_file_or_dict(secret) for secret in", "storage account found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace):", "'--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise", "= cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value", "identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable when assign", "user name cannot contain upper case character A-Z, special characters", "namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type", "subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not", "r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain upper case", "vault name :param str vault_name: name of the key vault", "os_type): \"\"\" Validates a parsed JSON array containing secrets for", "namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer", "namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\"", "Please use '--location' to specify a capable one. 'az vm", "errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd,", "> vnet_int: raise CLIError(error_msg) # format back to the cidr", "= re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count =", "missing sourceVault key at index {0} in arg {1}'.format( idx,", "can not be empty\") is_linux = (os_type.lower() == 'linux') #", "namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if", "= r'admin user name cannot contain upper case character A-Z,", "description='network balancer: application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer", "is_windows = os_type == 'windows' errors = [] try: loaded_secret", "prop in forbidden: forbidden.remove(prop) # set default storage SKU if", "'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC',", "namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect", "namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON", "# 'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath =", "#5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk:", "validation for the specific storage profile # start with the", "namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is None: if", "ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except", "and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\",", "return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions", "aval_sizes = [x.lower() for x in aval_sizes] if size not", "namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found", "exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding", "public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath", "if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath =", "elif not values: raise CLIError(\"No existing values found for '{0}'.", "if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type):", "not in secret or not secret['vaultCertificates']: err = 'Secret is", "find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace,", "# pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk", "namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing'", "CLIError('An RSA key file or key value must be supplied", "= StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: #", "--platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count > 100:", "is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def", "= next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()),", "if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: #", "zonal scale-sets\" elif namespace.instance_count > 100: err = \"'Standard' load", "parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if", "logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type =", "namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source(", "set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import", "name or None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type:", "'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers')", "'id' not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key", "-------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", "_validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils", "# region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type):", "password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise", "found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif", "std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect", "= _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and", "n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will", "\"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if", "source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os type", "ends with .' if re.findall(pattern, username): raise CLIError(linux_err if is_linux", "\"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't", "'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer',", "{1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']):", "}] :param dict secrets: Dict fitting the JSON description above", "logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope))", "# retrieve role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role)))", "'/disks/' in source.lower(): source_disk = source elif '/snapshots/' in source.lower():", "CLIError('--public-ip-address can only be used when creating a new load", "'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms',", "up your keys to a safe location.\", private_key_filepath, public_key_filepath) else:", "CoreOS Linux, Debian \"Stretch\" with backports kernel # Oracle Linux", "namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting", "raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from", "re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2)", "version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1]", "if len(password) not in range(min_length, max_length + 1): raise CLIError('The", "- 2 # try the other way around if (candidate_int", "\" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not", "api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client", "namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: #", "if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher']", "\" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet,", "namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if", "namespace) else: if kv and not is_valid_resource_id(kv): raise keyvault_usage def", "= re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+',", "result = None if not for_scale_set: result = next((s for", "specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified", "\"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\",", "figure out appropriate file names: # 'base_name'(with private keys), and", "elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load balancer", "candidate_int - 2 # try the other way around if", "if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region", "err = \"'Standard' load balancer is required for scale-sets with", "compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return", "'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms',", "resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type,", "EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError", "[--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re", "on Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise", "raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def", "def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles", "= 'new' logger.debug(\"specified NSG '%s' not found. It will be", "CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions", "if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower()", "lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will be missing", "logger.info('Use existing SSH public key file: %s', string_or_file) with open(string_or_file,", "return image.plan except CloudError as ex: logger.warning(\"Querying the image of", "sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'),", "else: # 4 - nothing specified - create a new", "= namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None)", "getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE", "gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace):", "namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name", "resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups')", "import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku", "yet \" \"supported. Please use '--location' to specify a capable", "namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0", "\"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\",", "if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found for", "return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size)", "'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info =", "VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what", "'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from", "_compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher,", "secret or not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates", "unmanaged OS disk from Azure Marketplace image' elif profile ==", "namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not", "image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version =", "DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot", "'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK", "index {0} in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg))", "with 100+ instances\" else: err = \"'Standard' load balancer is", "for zonal scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd,", "| --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot =", "(namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() ==", "\"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\",", "'%s'. Configuring plan settings \" \"will be skipped\", namespace.image, ex.message)", "raise CLIError('usage error: user assigned identity is only available under", "= 'existing' logger.debug(\"suitable existing storage account '%s' will be used\",", "found for '{0}'. Create one first and try \" \"again.\".format(option_name))", "'urn' # 3 - unmanaged vhd based images? if urlparse(namespace.image).scheme:", "namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err =", "pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id", "verify that the status of required and forbidden parameters validate_parameter_set(", "= matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn'", "# -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse import", "= '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not role_id:", "VMs need to be a supported image in the marketplace", "namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type", "readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role,", "array containing secrets for use in VM Creation Secrets JSON", "'r') as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if", "getattr(namespace, 'application_security_groups') ids = [] if names_or_ids == [\"\"] or", "'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools", "not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\")", "or ends with .' if re.findall(pattern, username): raise CLIError(linux_err if", "'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2',", "'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import", "resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import", "namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = []", "image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is", "1 return ((1 << (32 - mask)) - 2) >", "'%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id", "can't be used to create the VM/VMSS because availablity zone", "new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One", "capturing from VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx,", "def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source:", "elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden", "namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are", "mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len", "pylint: disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying the", "namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden =", "new load ' 'balancer or application gateway frontend.') namespace.public_ip_address =", "'new' logger.debug('no suitable storage account found. One will be created.')", "image based OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage,", "get_subscription_id nics_value = namespace.nics nics = [] if not nics_value:", "balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type =", "namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids =", "'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh'", "the project root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines", "'%s'\", storage_id['name']) else: # 2 - params for new storage", "to find an existing vnet and subnet in the target", "if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH", "os_type): import re is_linux = (os_type.lower() == 'linux') max_length =", "status of required and forbidden parameters validate_parameter_set( namespace, required, forbidden,", "import _compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__) def", "vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if", "'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP", "'^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None),", "= prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify", "== size), None) if size_info is None or size_info.number_of_cores <", "if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type',", "out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if", "is_valid_resource_id(val): return val kwargs = { 'name': val, 'resource_group': resource_group,", "namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if", "when capturing \" \"images from virtual machines\") except CloudError: namespace.os_blob_uri,", "generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS", "balancer_type = 'loadBalancer' else: # needed for Stack profile 2017_03_09", "\"'Standard' load balancer is required for scale-sets with 100+ instances\"", "== '': namespace.public_ip_address_type = None logger.debug('no public IP address will", "resolve the expected storage profile if getattr(namespace, 'attach_os_disk', None) and", "'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower()", "nics.append({ 'id': n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name,", "'%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet)", "validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username,", "def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is", "= _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if", "and '%s' have been generated under ~/.ssh to \" \"allow", "_resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is", "= StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE", "re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import", "list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}'", "secret: errors.append( 'Secret is missing sourceVault key at index {0}", "= _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from", "--source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source(", "'^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for", "namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing", "image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member", "[] try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except", "in target resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing'", "parameters to resolve the expected storage profile if getattr(namespace, 'attach_os_disk',", "group from vault name :param str vault_name: name of the", "'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3',", "'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo',", "n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces',", "not hasattr(temp, 'location_info'): return if not temp or not [x", "general requirements, but is specifically disallowed for this image. Please", "os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing", "open(string_or_file, 'r') as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content):", "# Resolve the type of balancer (if any) being used", "index {0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in", "'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise", "namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application", "'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o,", "logger.debug(\"load balancer '%s' not found. It will be created.\", namespace.load_balancer)", "source elif '/disks/' in source.lower(): source_disk = source elif '/snapshots/'", "resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace,", "elif '/disks/' in source.lower(): source_disk = source elif '/snapshots/' in", "disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except", "vnet information needed to verify the defaults we are coming", "namespace.nics nics = [] if not nics_value: namespace.nic_type = 'new'", "and will be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType", "namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name !=", "'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo',", "'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3',", "non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type ==", "_validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile", "CLIError(error_msg) # format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int", "if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i < 16:", "'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version", "'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C']", "role_id: # retrieve role id role_defs = list(client.list(scope, \"roleName eq", "one role matches the given name '{}'. Please pick an", "_compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd,", "_validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden =", "required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required =", "size), None) if size_info is None or size_info.number_of_cores < 8:", "Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if", "must be supplied to SSH Key Value. ' 'You can", "not found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway ==", "placement group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if", "if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required =", "matches the VM's location sku_tier = 'Premium' if 'Premium' in", "not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx,", "\"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\",", "load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images if x['urnAlias'].lower()", "set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg,", "if len(values) > 1: raise CLIError(\"Multiple possible values found for", "== 'ssh': raise CLIError('SSH not supported for Windows VMs.') #", "image \"{}\". Use a custom image name, id, or pick", "namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace):", "file: %s', string_or_file) with open(string_or_file, 'r') as f: content =", "be used when --public-ip-per-vm is enabled') if namespace.eviction_policy and not", "= ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo',", "key file or key value must be supplied to SSH", "the authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value or", "nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and", "def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network',", "to let CLI generate one for you') namespace.ssh_key_value = content", "CLIError(\"No existing values found for '{0}'. Create one first and", "'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD", "missing {0} within vaultCertificates array at secret ' \\ 'index", "'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if namespace.load_balancer:", "not found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer ==", "# region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically", "for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal parameters to", "image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS", "import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles", "_validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and", "#3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile", "s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def", "if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from a", "matched = next((x for x in images if x['urnAlias'].lower() ==", "ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource group that", "if for_scale_set: # VMSS lacks some parameters, so scrub these", "not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for", "namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer", "o, s in distros: if p.lower() == publisher and (o", "\"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This", "in secrets] except Exception as err: raise CLIError('Error decoding secrets:", "= as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'):", "compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image,", "for val in names_or_ids: if not is_valid_resource_id(val): val = resource_id(", "IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if", "None) if not result: continue namespace.subnet = result.name namespace.vnet_name =", "gateway '%s' not found. It will be created.\", namespace.application_gateway) elif", "msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "True # Now verify that the status of required and", "elif '/snapshots/' in source.lower(): source_snapshot = source else: compute_client =", "[] from ._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities):", "temp or not [x for x in (temp.location_info or [])", "== 'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif", "prop in props_to_remove: if prop in required: required.remove(prop) if prop", "if namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities: raise", "supplied for the --image parameter. Updates the namespace and returns", "24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b,", "os try: from urllib.parse import urlparse except ImportError: from urlparse", "(if any) being used balancer_type = 'None' if namespace.load_balancer is", "namespace.platform_fault_domain_count is not None and namespace.zones is None: raise CLIError('usage", "doesn't implement location_info property if not hasattr(temp, 'location_info'): return if", "such needs so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles", "for over-provision factor = 1.5 if over_provision else 1 return", "examining the OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower()", "authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path:", "'urn' # 5 - check if an existing managed disk", "def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory", "vnet_int: raise CLIError(error_msg) # format back to the cidr candaidate_str", "= client.get(resource_group, balancer_name) values = [x.name for x in balancer.backend_address_pools]", "elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application gateway", "elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file", "for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet =", "SSH access to the VM. If using machines without \"", "['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name',", "raise CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images from", "'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk:", "storage profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if", "parsed JSON array containing secrets for use in VM Creation", "from_set_command or namespace.assign_identity is not None: identities = namespace.assign_identity or", "== location and v.subnets): # 1 - find a suitable", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx,", "_get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools", "ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku ==", "used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load", "client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role,", "missing ssh/rdp, so warn here. logger.warning(\"No inbound nat pool was", "None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single placement", "= get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I):", "user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet", "image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source):", "'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] +", "if errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators def", "StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb']", "= size.lower() # to refresh the list, run 'az vm", "new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account", "image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk", "d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value", "and a.location == namespace.location), None) if account: # 3 -", "set default storage SKU if not provided and using an", "s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for", "'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested',", "== bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID |", "'{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values:", "missing sourceVault.id key at index {0} in arg {1}'.format( idx,", "32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int", "azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if", "= namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv): raise", "uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client", "placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer'", "'{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import", "have enough leeway for over-provision factor = 1.5 if over_provision", "and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only", "'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer')", "error: --subnet-address-prefix value should be a subrange of --vnet-address-prefix's\" #", "keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault", "specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return #", "Standard_DS1_v2' and # get it from the error aval_sizes =", "namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location", "'--single-placement-group' should be turned off for zonal scale-sets or with\"", "CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\",", "`~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in [contains_lower, contains_upper,", "= _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def", "= True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix", "x.zones]: raise CLIError(\"{}'s location can't be used to create the", "= vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet", "Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed", "prop in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) #", "# try the other way around if (candidate_int >> (vnet_bit_mask_len", "from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x", "'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo',", "pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots =", "val kwargs = { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace,", "defaulting to '%s' under because single placement group is disabled\",", "if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does not", "= compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x", "output as logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx,", "= [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'),", "disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif not", "\"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\",", "process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion =", "in namespace.target_regions: parts = t.split('=', 1) if len(parts) == 1:", ":rtype: list \"\"\" is_windows = os_type == 'windows' errors =", "import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder", "x in new_4core_sizes] if size not in new_4core_sizes: compute_client =", "candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2),", "Systematically determines what type is supplied for the --image parameter.", "is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup", "pylint:disable=too-many-lines import os try: from urllib.parse import urlparse except ImportError:", "for prop in props_to_remove: if prop in required: required.remove(prop) if", "created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from", "= re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer =", "check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing", "if not namespace.authentication_type: # apply default auth type (password for", "balancer_type = 'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway'", "namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be used when", "publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical',", "2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if", "\"\"\" Fetch resource group from vault name :param str vault_name:", "namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx,", "None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks',", "in kwargs.items() if not v} return resource_id(**kwargs) if not missing_kwargs", "namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) ==", "= compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot)", "attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx,", "CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve", "storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1", "if a.sku.tier.value == sku_tier and a.location == namespace.location), None) if", "images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher =", "== publisher and (o is None or o.lower() == offer)", "account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not", "resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val", "target resource group that matches the VM's location with a", "suitable subnet found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count,", "'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden,", "namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris =", "profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS", "from VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source,", "= publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse',", "urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4)", "client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group']", "logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else: # 2", "'uri' # 4 - attempt to match an URN alias", "list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos =", "'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2',", "in sizes if s.name.lower() == size), None) if size_info is", "None source_snapshot = None if urlparse(source).scheme: # a uri? source_blob_uri", "= info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault", "and namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK)", "regions_info = [] for t in namespace.target_regions: parts = t.split('=',", "namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing'", "r'admin user name cannot contain upper case character A-Z, special", "- nothing specified - find viable storage account in target", "\"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\",", "not found. It will be created.\", namespace.nsg) elif namespace.nsg ==", "lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb:", "from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re", "parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return None def", "settings \" \"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements", "required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile", "namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd,", "subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids)", "to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False):", "import re if not username: raise CLIError(\"admin user name can", "be missing ssh/rdp, so warn here. logger.warning(\"No inbound nat pool", "None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try:", "vault_name: name of the key vault :return: resource group name", "(v for v in client.list(rg) if v.location == location and", "specified - find viable storage account in target resource group", "== 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile =", "x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return", "ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx,", "_get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import", "re.I): role_id = role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format(", "to refresh the list, run 'az vm create --accelerated-networking --size", "namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type:", "\"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names:", "msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name,", "vnet/subnet result = None if not for_scale_set: result = next((s", "for x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed", "created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no", "to the VM. If using machines without \" \"permanent storage,", "[_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if", "Please try a different value.\".format(username)) return username def _validate_admin_password(password, os_type):", "namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace):", "\"instance count '{}' is out of range of 2^16 subnet", "= re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[", "from_set_command=False): if from_set_command or namespace.assign_identity is not None: identities =", "= LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group is", "'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s',", "matches the VM's location with a matching subnet for vnet_match", "load ' 'balancer or application gateway frontend.') namespace.public_ip_address = ''", "['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in", "namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not found and", "for this image. Please try a different value.\".format(username)) return username", "'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes]", "namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets:", "balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None)", "'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass,", "\"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\",", "on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing", "1 - find a suitable existing vnet/subnet result = None", "None: identities = namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID", "for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting", "!= MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if", "= res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when", "not isinstance(nics_value, list): nics_value = [nics_value] for n in nics_value:", "_validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'):", "namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using", "CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel #", "'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for", "string os_type: the type of OS (linux or windows) :return:", "not namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify '--os-type'", "yet for VMSS, so use 'getattr' to avoid crash namespace.disk_info", "namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address", "as f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys:", "role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not", "Creation Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\" },", "balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name", "= next((x for x in sku_infos if x.name.lower() == size_info.lower()),", "--subnet-address-prefix value should be a subrange of --vnet-address-prefix's\" # extract", "= \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if", "supported for Windows VMs.') # validate proper arguments supplied based", "- create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable", "None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr,", "= '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix", "next((s for s in sizes if s.name.lower() == size), None)", "namespace.nic_type = 'new' logger.debug('new NIC will be created') return if", "namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden =", "validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import", "x in sku_infos if x.name.lower() == size_info.lower()), None) # For", "d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not", "[contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if", "error: '--role {}' is not applicable as the '--scope' is", "cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if", "not applicable as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities", "type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n } })", "CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from", "not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type", "ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source)", "process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = []", "if not namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify", "# 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing'", "namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password':", "user name can not be empty\") is_linux = (os_type.lower() ==", "namespace.application_gateway == '': namespace.app_gateway_type = None logger.debug('no application gateway will", "StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching',", "and v.subnets): # 1 - find a suitable existing vnet/subnet", "returns the type for subsequent processing. \"\"\" from msrestazure.tools import", "is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage:", "if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID |", "required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type ==", "raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids", "raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace):", "res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'],", "minimum Compute API version of 2017-12-01') if namespace.identity_scope: if identities", "# endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group,", "scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name", "'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3',", "= '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import", "else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found. It", "namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True", "i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] =", "use minimal parameters to resolve the expected storage profile if", "used to create the VM/VMSS because availablity zone is not", "lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise", "not namespace.disable_overprovision) result = next((s for s in vnet_match.subnets if", "exposed for VM. VMSS has no such needs so far", "== StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk',", "def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client =", "'{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix =", "subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics", "is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs", "err = \"instance count '{}' is out of range of", "(vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back", "CLIError('Password must have the 3 of the following: 1 lower", "the given name '{}'. Please pick an id from '{}'\"", "None and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT", "logger.debug(\"specified NSG '%s' not found. It will be created.\", namespace.nsg)", "and not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif", "public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4]", "for the --image parameter. Updates the namespace and returns the", "LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group is turned", "cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in", "resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else:", "'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does", "username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\",", "n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if", "not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s'", "namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public IP address", "_figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise", "special characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username):", "VMSS has no such needs so far if getattr(namespace, 'public_ip_sku',", "namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: #", "in the marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL", "'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise", "keys to a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An", "\\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools)", "= '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg =", "or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if", "LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer is required", "= 'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace):", "def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage", "'%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create a new", "raise CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd, namespace):", "in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s):", "namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public", "It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type", "so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType", "private keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if", "if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible", "and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count", "resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "forbidden: forbidden.remove(prop) # set default storage SKU if not provided", "namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except CloudError", "image name, id, or pick one from {}' raise CLIError(err.format(namespace.image,", "Please pick an id from '{}'\" raise CLIError(err.format(role, ids)) role_id", "disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or", "available under profile ' 'with minimum Compute API version of", "for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if", "3 - create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no", "= compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or", "if namespace.admin_password: raise ValueError('Admin password cannot be used with SSH", "3: raise CLIError('Password must have the 3 of the following:", "{0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in", "for use in VM Creation Secrets JSON structure [{ \"sourceVault\":", "'{}' does not exist.\".format(subnet)) elif subnet_exists: # 2 - user", "= namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids", "except NoTTYException: raise CLIError('Please specify password in non-interactive mode.') #", "resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx,", "except CloudError: err = 'Invalid image \"{}\". Use a custom", "type: {}'.format(image_type)) else: # did not specify image XOR attach-os-disk", "else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None:", "and not subnet and not nics: logger.debug('no subnet specified. Attempting", "def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault')", "source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not", "'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes]", "provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in identities if", "from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing from", "'You can use --generate-ssh-keys to let CLI generate one for", "2) error_msg = \"usage error: --subnet-address-prefix value should be a", "= account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s'", "+ auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile", "'new' logger.debug('new NIC will be created') return if not isinstance(nics_value,", "sku_tier and a.location == namespace.location), None) if account: # 3", "= [x.lower() for x in aval_sizes] if size not in", "identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default',", "not found and will be created\", storage_id['name']) else: from azure.cli.core.profiles", "password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif", "#1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile", "images? if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to", "s in distros: if p.lower() == publisher and (o is", "contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit =", "elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway", "network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return", "'usage error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id", "STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE", "is not applicable as the '--scope' is not provided\".format( namespace.identity_role))", "return username def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower()", "try capturing from VM, a most common scenario res_id =", "_validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'):", "namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan =", "resource group that matches the VM's location with a matching", ".' if re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err)", "required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network", "namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE", "user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with", "existing SSH public key file: %s', string_or_file) with open(string_or_file, 'r')", "required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk']", "1.5 if over_provision else 1 return ((1 << (32 -", "VMs.') # validate proper arguments supplied based on the authentication", "in disallowed_user_names: raise CLIError(\"This user name '{}' meets the general", "not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) >", "return if not isinstance(nics_value, list): nics_value = [nics_value] for n", "be used with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path:", "image_version_infos: raise CLIError('There is no latest image version exists for", "\\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err = r'admin", "Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku", "namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if", "group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif", "namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error:", "namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot:", "False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned", "nics_value = namespace.nics nics = [] if not nics_value: namespace.nic_type", "namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku ==", "\"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import", "user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity", "gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower()", "= _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if", "(assumes it is an image ID) if is_valid_resource_id(namespace.image): return 'image_id'", "None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False", "elif image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile =", "info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk,", "public key file: %s', string_or_file) with open(string_or_file, 'r') as f:", "kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv", "STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id':", "plan settings \" \"will be skipped\", namespace.image, ex.message) # pylint:", "and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch", "'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile", "for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type',", "if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "- find viable storage account in target resource group namespace.storage_account", "rg = namespace.resource_group_name nic_ids = [] for n in namespace.nics:", "namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version", "key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'],", "import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x", "'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo',", "try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True)", "resource group from vault name :param str vault_name: name of", "= f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out", "res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() ==", "for VMSS, so use 'getattr' to avoid crash namespace.disk_info =", "check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified", "_get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic =", "what type is supplied for the --image parameter. Updates the", "[x for x in identities if x != MSI_LOCAL_ID] if", "vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask)", "~/.ssh to \" \"allow SSH access to the VM. If", "validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks',", "= ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type',", "res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id)", "ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import", "'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used') def", "from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri", "namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except", "requirements, but is specifically disallowed for this image. Please try", "if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs)", "'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway':", "from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from", "namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def", "location with a matching subnet for vnet_match in (v for", "secret and 'id' not in secret['sourceVault']: errors.append( 'Secret is missing", "parameter. Updates the namespace and returns the type for subsequent", "= True # Now verify that the status of required", "created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2'", "= namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location =", "'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3',", "for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d)", "'nics', None) if not vnet and not subnet and not", "= 'loadBalancer' if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o", "over-provision factor = 1.5 if over_provision else 1 return ((1", "a fully-qualified ID (assumes it is an image ID) if", "and (o is None or o.lower() == offer) and (s", "if namespace.zones: err = \"'Standard' load balancer is required for", "[x for x in (temp.location_info or []) if x.zones]: raise", "namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re", "namespace.target_regions: parts = t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0]))", "in (v for v in client.list(rg) if v.location == location", "{2} in arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl',", "namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku)", "a matching subnet for vnet_match in (v for v in", "required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace,", "--vnet-address-prefix's\" # extract vnet information needed to verify the defaults", "forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name')", "(candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int", "check if an existing managed disk image resource compute_client =", "'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower() for x", "EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id):", "# needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if", "vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len)", "is no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info =", "\"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile):", "== namespace.location), None) if account: # 3 - nothing specified", "size_info = next((s for s in sizes if s.name.lower() ==", "data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name,", "if re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err) if", "source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults',", "if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is", "validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def", "secret ' \\ 'index {1} and vaultCertificate index {2} in", "resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] ==", "namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching)", "because availablity zone is not yet \" \"supported. Please use", "'image_id' # 2 - attempt to match an URN pattern", "Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg,", "storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id", "= content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity", "and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway", "return # VMs need to be a supported image in", "be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if", "\"\"\" Validates a parsed JSON array containing secrets for use", "namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx,", "namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found.", "enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority", "12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\"", "int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None:", "for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden", "StorageProfile import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from", "[x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions", "'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3',", "namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise", "[nics_value] for n in nics_value: nics.append({ 'id': n if '/'", "get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id", "'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo',", "sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat',", "from ._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities): if", "and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24)", "in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not", "= 'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else:", "role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not", "role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1:", "'%s' not found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway", "in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors))", "in target resource group that matches the VM's location with", "'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info #", "'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux',", "'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3',", "validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace):", "will be created') return if not isinstance(nics_value, list): nics_value =", "import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics", "\\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway", "'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name,", "'{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id", "props_to_remove: if prop in required: required.remove(prop) if prop in forbidden:", "_validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin", "elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe']", "lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp, so warn", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile", "resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics =", "argument.\") if not namespace.authentication_type: # apply default auth type (password", "next((x for x in sku_infos if x.name.lower() == size_info.lower()), None)", "= None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if", "azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name", "CLIError(\"usage error: '--scope'/'--role' is only applicable when assign system identity\")", "= namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not", "0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from", "!= AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd,", "None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address will be", "will be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type =", "namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd,", "raise ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME]", "#4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type))", "'%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet:", "_validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets,", "{1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret or not", "\"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault')", "if not publisher: return publisher, offer, sku = publisher.lower(), offer.lower(),", "next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None)", "namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions:", "if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing \"", "group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones:", "#2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE", "SKU is only exposed for VM. VMSS has no such", "# STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type ==", "vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}'", "return 'image_id' # 2 - attempt to match an URN", "publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles',", "namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace)", "pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1)", "def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network')", "a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines',", "_validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id =", "pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif", "range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name,", "matched['version'] return 'urn' # 5 - check if an existing", "a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key", "= 'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name,", "is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr,", "- create a new storage account namespace.storage_account_type = 'new' logger.debug('no", "if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)),", "idx_arg)) if 'sourceVault' in secret and 'id' not in secret['sourceVault']:", "= source elif '/disks/' in source.lower(): source_disk = source elif", "storage account in target resource group namespace.storage_account = account.name namespace.storage_account_type", "2016, Windows Server 2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer,", "= [x.name for x in balancer.backend_address_pools] if len(values) > 1:", "name cannot contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()!", "is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope", "the general requirements, but is specifically disallowed for this image.", "None) or getattr(namespace, 'vm_sku', None) size = size.lower() # to", "only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage", "in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo',", "system identity\") # keep 'identity_role' for output as logical name", "or []) if x.zones]: raise CLIError(\"{}'s location can't be used", "getattr(namespace, 'nics', None) if not vnet and not subnet and", "the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2),", "process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd,", "v.location == location and v.subnets): # 1 - find a", "start with $ or -' win_err = r'admin user name", "_validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if", "azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name =", "if namespace.single_placement_group is not False else 'applicationGateway' logger.debug(\"W/o STD LB,", "rg = namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv):", "if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes =", "for x in sku_infos if x.name.lower() == size_info.lower()), None) #", "| \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx,", "vnet_match in (v for v in client.list(rg) if v.location ==", "or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type 'password': \"", "_validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace)", "if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \"", "'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set", "return 'urn' # 3 - unmanaged vhd based images? if", "else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask", "logger.debug('new load balancer will be created') if namespace.load_balancer_type == 'new'", "an URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images", "values = [x.name for x in balancer.backend_address_pools] if len(values) >", "validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if", "1 number and 1 special character') def validate_ssh_key(namespace): string_or_file =", "from knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password", "raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx,", "instances\" else: err = \"'Standard' load balancer is required because", "namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True)", "distros: if p.lower() == publisher and (o is None or", "range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if", "!= MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') #", "cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation:", "as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise", "import StorageProfile import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory", "azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from ._actions import", "attempt to match an URN alias (most likely) from azure.cli.command_modules.vm._actions", "specified - create a new storage account namespace.storage_account_type = 'new'", "resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name,", "decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx,", "- nothing specified - create a new storage account namespace.storage_account_type", "if (subnet_is_id and vnet) or (not subnet_is_id and not vnet):", "from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg", "usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists", "publisher: return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros", "'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2',", "VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden =", "._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] !=", "custom image name, id, or pick one from {}' raise", "in target resource group that matches the VM's location sku_tier", "# Now verify that the status of required and forbidden", "= None source_snapshot = None if urlparse(source).scheme: # a uri?", "error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions", "length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults',", "resource group name or None :rtype: str \"\"\" from azure.cli.core.profiles", "resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace):", "subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not", "fitting the JSON description above :param string os_type: the type", "namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id", "or None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from", "def _resolve_role_id(cli_ctx, role, scope): import re import uuid from azure.cli.core.commands.client_factory", "being used balancer_type = 'None' if namespace.load_balancer is None and", "None) if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer", "'.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated", "resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group):", "for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing", "find viable storage account in target resource group namespace.storage_account =", "find VNET in target resource group that matches the VM's", "address will be created') # Public-IP SKU is only exposed", "CloudError source_blob_uri = None source_disk = None source_snapshot = None", "namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace,", "compute_client.disks.get(resource_group_name, source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def", "'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for", "import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType", "def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is supplied", "'^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o, s", "namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile ==", "'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage:", "idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if", "'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName',", "if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when creating", "namespace.generate_ssh_keys: # figure out appropriate file names: # 'base_name'(with private", "def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones is", "description='network balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name)", "'/snapshots/' in source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx)", "{}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract", "= ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params", "not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \"", "namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG will be", "if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if", "if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type =", "error: '--scope'/'--role' is only applicable when assign system identity\") #", "if is_valid_resource_id(val): return val kwargs = { 'name': val, 'resource_group':", "in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore'", "subnet in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks #", "is None or re.match(s, sku, re.I)): namespace.accelerated_networking = True def", "\"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\",", "'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if", "namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory", "namespace.nsg_type = 'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd,", "else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError:", "= [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type", "sourceVault.id key at index {0} in arg {1}'.format( idx, idx_arg))", "= _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client", "not in secret: errors.append( 'Secret is missing sourceVault key at", "one. 'az vm list-skus' can be \" \"used to find", "usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault,", "vault_name): \"\"\" Fetch resource group from vault name :param str", "if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len)", "out appropriate file names: # 'base_name'(with private keys), and 'base_name.pub'(with", "import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source", "be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type = None", "> 1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify", "info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info", "return 'create managed OS disk from Azure Marketplace image' elif", "namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or", "result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s'", "err = 'Invalid image \"{}\". Use a custom image name,", "\"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\",", "be a subrange of --vnet-address-prefix's\" # extract vnet information needed", "information needed to verify the defaults we are coming out", "'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required", "for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try:", "namespace.vnet_name, namespace.subnet) return # 3 - create a new vnet/subnet", "not nics: logger.debug('no subnet specified. Attempting to find an existing", "'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2',", "namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace):", "{} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper =", "storage, back up your keys to a safe location.\", private_key_filepath,", "if not v} return resource_id(**kwargs) if not missing_kwargs else None", "use --generate-ssh-keys to let CLI generate one for you') namespace.ssh_key_value", "(source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault,", "= resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace,", "profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters,", "} }) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type =", "\"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot =", "= t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try:", "== 'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0]", "be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx,", "not vnet and not subnet and not nics: logger.debug('no subnet", "type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name for", "logger.debug('new public IP address will be created') # Public-IP SKU", "from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name", "nics = [] if not nics_value: namespace.nic_type = 'new' logger.debug('new", "in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i],", "'properties': { 'primary': nics_value[0] == n } }) namespace.nics =", "namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask):", "URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher =", "val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx,", "= parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type", "as single placement group is turned off\") elif namespace.load_balancer_sku ==", "pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create", "urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace)", "namespace.target_regions: regions_info = [] for t in namespace.target_regions: parts =", "<= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1", "image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' #", "CLIError('SSH not supported for Windows VMs.') # validate proper arguments", "public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have been generated", "compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name,", "not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long", "disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name,", "Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage)", "'': namespace.load_balancer_type = None logger.debug('no load balancer will be used')", "in the project root for license information. # -------------------------------------------------------------------------------------------- #", "= ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk',", "raise CLIError('usage error: --license-type is only applicable on Windows VM')", "for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx,", "in source.lower(): source_disk = source elif '/snapshots/' in source.lower(): source_snapshot", "v} return resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx,", "== StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk' elif", "= cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not", "we are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len =", "= _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s", "vnet and subnet in the target resource group client =", "pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name", "(namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file):", "TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t", "using an image based OS if not namespace.storage_sku and namespace.storage_profile", "be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False", "error: user assigned identity is only available under profile '", "'{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n", "image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image =", "', '.join(values))) elif not values: raise CLIError(\"No existing values found", "CLIError(\"usage error: '--single-placement-group' should be turned off for zonal scale-sets", "None: namespace.ultra_ssd_enabled = True # Now verify that the status", "the VM's location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku", "= [nics_value] for n in nics_value: nics.append({ 'id': n if", "namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type ==", "['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway')", "managed custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription'])", "be \" \"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches,", "_validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and", "is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name:", "character, 1 number and 1 special character') def validate_ssh_key(namespace): string_or_file", "return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet)", "[]), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import", "or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions", "'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC',", "= [r.id for r in role_defs] err = \"More than", "in forbidden: forbidden.remove(prop) # set default storage SKU if not", "= _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError:", "_validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr", "specifically disallowed for this image. Please try a different value.\".format(username))", "NAME_OR_ID') # Resolve the type of balancer (if any) being", "= namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified", "Licensed under the MIT License. See License.txt in the project", "'new' logger.debug(\"application gateway '%s' not found. It will be created.\",", "_validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace)", "for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] =", "will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new'", "license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from", "\" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError", "'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2',", "'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required =", "jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0}", "from urlparse import urlparse # pylint: disable=import-error from knack.log import", "in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set", "is only applicable when assign system identity\") # keep 'identity_role'", "'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16',", "['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation", "rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace)", "placement group' is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx):", "= [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks]", "'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2',", "= next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'),", "array or it is empty at index {0} in '", "urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer", "# 3 - unmanaged vhd based images? if urlparse(namespace.image).scheme: return", "= ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if", "# '2' are the reserved broadcasting addresses # '*1.5' so", "compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes if s.name.lower()", "0 for i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count,", "is not None: identities = namespace.assign_identity or [] from ._vm_utils", "in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku,", "namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group = False", "STD LB, defaulting to '%s' under because single placement group", "import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except", "unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri' # 4", "# find VNET in target resource group that matches the", "str vault_name: name of the key vault :return: resource group", "type of balancer (if any) being used balancer_type = 'None'", "None) is None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role", "disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots = []", "CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names =", "x]) # pylint: disable=line-too-long if count < 3: raise CLIError('Password", "Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not", "NAME | --keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name", "image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher", "normalize_disk_info # attach_data_disks are not exposed yet for VMSS, so", "contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char =", "_get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) >", "namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if", "--keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name if rg:", "validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv): raise keyvault_usage", "parse_resource_id # use minimal parameters to resolve the expected storage", "'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet)", "namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri,", "if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku =", "subnet specified. Attempting to find an existing Vnet and subnet...')", "import normalize_disk_info # attach_data_disks are not exposed yet for VMSS,", "resource group that matches the VM's location sku_tier = 'Premium'", "API version of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID", "if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else:", "within vaultCertificates array at secret ' \\ 'index {1} and", "client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized", "namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing \" \"images", "existing Vnet and subnet...') # if nothing specified, try to", "= _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product =", "of required and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage", "not image_version_infos: raise CLIError('There is no latest image version exists", "is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku", "from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try:", "region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name", "def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask =", "compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine =", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client =", "the defaults we are coming out vnet_ip_address, mask = vnet_cidr.split('/')", "'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk", "'single placement group' is turned off\" raise CLIError('usage error:{}'.format(err)) def", "namespace.resource_group_name if rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage", "contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count", "namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error:", "identities = namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for", "size_info.lower()), None) # For Stack (compute - 2017-03-30), Resource_sku doesn't", "namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import", "setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id", "s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask,", "namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk", "proper arguments supplied based on the authentication type if namespace.authentication_type", "private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file or key", "= get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators", "== StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account',", "subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import", "= [] if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC", "location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA key file or", "if sku and sku.lower() not in [x.lower() for x in", "5 - check if an existing managed disk image resource", "namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name',", "from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx,", "\"usage error: --subnet-address-prefix value should be a subrange of --vnet-address-prefix's\"", "None logger.debug('no application gateway will be used') elif namespace.application_gateway is", "msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() ==", "nics_value: nics.append({ 'id': n if '/' in n else resource_id(name=n,", "# 3 - create a new vnet/subnet namespace.vnet_type = 'new'", "index {0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not", "'{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault,", "crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching,", "subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type", "== 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value", "based OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]:", "a managed custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx,", "hasattr(temp, 'location_info'): return if not temp or not [x for", "raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member", "characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username): raise", "own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace)", "# pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot =", "'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC',", "2 - attempt to match an URN pattern urn_match =", "raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from", "if kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name):", "# pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+')", "OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows'", "account found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from", "\"allow SSH access to the VM. If using machines without", "= [validate_file_or_dict(secret) for secret in secrets] except Exception as err:", "forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required", "def _convert_to_int(address, bit_mask_len): a, b, c, d = [int(x) for", "used') elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG", "key vault :return: resource group name or None :rtype: str", "first and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if", "len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values found for '{0}':", "specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new'", "namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move", "from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower()", "# pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools", "LB, defaulting to '%s' under because single placement group is", "for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret):", "forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile ==", "re # 1 - check if a fully-qualified ID (assumes", "import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re # 1", "' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message", "namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage", "most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute')", "= res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos =", "can be \" \"used to find such locations\".format(namespace.resource_group_name)) # pylint:", "get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for", "'Secret is missing sourceVault key at index {0} in arg", "= storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): #", "try to find an existing vnet and subnet in the", "'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC',", "logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type", "namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no load", "subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) >", ":param str vault_name: name of the key vault :return: resource", "subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back to the", "identity is only available under profile ' 'with minimum Compute", "}] }] :param dict secrets: Dict fitting the JSON description", "1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count =", "elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public IP", "'sourceVault' not in secret: errors.append( 'Secret is missing sourceVault key", "= normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def", "load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name =", "def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri =", "is_linux else 123 min_length = 12 if len(password) not in", "reserved broadcasting addresses # '*1.5' so we have enough leeway", "None or o.lower() == offer) and (s is None or", "n in nics_value: nics.append({ 'id': n if '/' in n", "be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) #", "LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku =", "is out of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count))", "# format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int <<", "_figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None", "= \"instance count '{}' is out of range of 2^16", "'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2',", "to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd,", "OS disk from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk:", "and returns the type for subsequent processing. \"\"\" from msrestazure.tools", "nat pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name =", "and not nics: logger.debug('no subnet specified. Attempting to find an", "pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if", "# 1 - existing storage account specified namespace.storage_account_type = 'existing'", "error '%s'. Configuring plan settings \" \"will be skipped\", namespace.image,", "= cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids", "used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public", "n } }) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type", "image. Please try a different value.\".format(username)) return username def _validate_admin_password(password,", "'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None:", "if profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk created", "'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under because single", "disk from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return", "usage_error = 'usage error: --source {SNAPSHOT | DISK} | --source", "namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address)", "StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type =", "if names_or_ids == [\"\"] or not names_or_ids: return for val", "'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2',", "= _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location,", "'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else: #", "default storage SKU if not provided and using an image", "namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name =", "backports kernel # Oracle Linux 7.4, Windows Server 2016, Windows", "_get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids", "resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target", "the image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name,", "# VMs need to be a supported image in the", "applicable on Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name:", "{1} and vaultCertificate index {2} in arg {3}' if 'certificateUrl'", "raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not specify", "elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk'", "image_version) # pylint: disable=no-member return image.plan except CloudError as ex:", "f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate", "License.txt in the project root for license information. # --------------------------------------------------------------------------------------------", "nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be created') return", "= 'new' logger.debug('no suitable storage account found. One will be", "n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic:", "is empty at index {0} in ' \\ 'arg {1}", "vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and subnet", "confirm=True) except NoTTYException: raise CLIError('Please specify password in non-interactive mode.')", "the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for", "from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk = None", "namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is only applicable", "namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type)", "in sku_infos if x.name.lower() == size_info.lower()), None) # For Stack", "role_id = role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id,", "== '': namespace.nsg_type = None logger.debug('no NSG will be used')", "CLIError(\"Role '{}' doesn't exist.\".format(role)) elif len(role_defs) > 1: ids =", "if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if", "DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] #", "if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)):", "OS (linux or windows) :return: errors if any were found", "vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet =", "arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret and 'id'", "_subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are the", "except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import", "import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags)", "'--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x", "namespace.subnet) return # 3 - create a new vnet/subnet namespace.vnet_type", "_get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its", "for new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage", "2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if", "import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions", "_validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups',", "enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret is missing", "is supplied for the --image parameter. Updates the namespace and", "== 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg =", "namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD", "MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i]", "Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2 publisher,", "'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC',", "namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing", "except ValueError: raise CLIError(\"usage error: {}'s replica count must be", "else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\",", "a capable one. 'az vm list-skus' can be \" \"used", "f: content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: #", "if prop in forbidden: forbidden.remove(prop) # set default storage SKU", "get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return", "'Secret is missing vaultCertificates array or it is empty at", "namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id'", "the specific storage profile # start with the required/forbidden parameters", "raise CLIError(\"No existing values found for '{0}'. Create one first", "vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet '%s'", "StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else:", "'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo',", "namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information from a managed", "in secret or not secret['vaultCertificates']: err = 'Secret is missing", "matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku']", "msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val):", "jdx, idx_arg)) if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore',", "{3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg))", "'.join(values))) elif not values: raise CLIError(\"No existing values found for", "= next((s for s in sizes if s.name.lower() == size),", "size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC',", "raise CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\") if", "= get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id)", "= getattr(namespace, 'nics', None) if not vnet and not subnet", "profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom", "- 2017-03-30), Resource_sku doesn't implement location_info property if not hasattr(temp,", "rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists:", "nics_value = [nics_value] for n in nics_value: nics.append({ 'id': n", "or namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group =", "so scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop", "[]) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'])", "secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at index {0}", "re.findall(pattern, username): raise CLIError(linux_err if is_linux else win_err) if is_linux", "be created') # AppGateway frontend required = [] if namespace.app_gateway_type", "vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3", "'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file", "try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd,", "for Windows VMs.') # validate proper arguments supplied based on", "in new_4core_sizes] if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx)", "hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name,", "1 lower case character, 1 upper case character, 1 number", "secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array or it", "v in client.list(rg) if v.location == location and v.subnets): #", "= namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace):", "allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info", "from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles", "return ((1 << (32 - mask)) - 2) > int(vmss_instance_count", "gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway", "if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name')", "vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address,", "vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are the reserved", "VMSS, so use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num,", "specified existing storage account '%s'\", storage_id['name']) else: # 2 -", "aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2',", "information from a managed custom image res = parse_resource_id(namespace.image) compute_client", "validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def", "'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the specific storage", "== 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif", "nics_value[0] == n } }) namespace.nics = nics namespace.nic_type =", "namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not", "Windows VMs.') # validate proper arguments supplied based on the", "return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None:", "- find a suitable existing vnet/subnet result = None if", "'{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2),", "public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath", "logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace,", "a subrange of --vnet-address-prefix's\" # extract vnet information needed to", "import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name,", "(temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location can't be", "None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod',", "type if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise", "load balancer is required for zonal scale-sets\" elif namespace.instance_count >", "found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer == '':", "return 'image_id' except CloudError: err = 'Invalid image \"{}\". Use", "--size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk", "image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product", "size_info): from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace)", "hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import", "--attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value']", "namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 -", "= _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name,", "== StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure Marketplace", "Public-IP SKU is only exposed for VM. VMSS has no", "A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -'", "raise CLIError(\"This user name '{}' meets the general requirements, but", "= parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name", "if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx,", "nics = getattr(namespace, 'nics', None) if not vnet and not", "not lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp, so", "getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error: --assign-identity [--scope", "key file: %s', string_or_file) with open(string_or_file, 'r') as f: content", "'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms',", "msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics", "machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source)", "sku and sku.lower() not in [x.lower() for x in allowed_skus]:", "def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged OS", "data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account:", "can only be used when creating a new load '", "be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions = regions_info # endregion", "logger.warning(\"No inbound nat pool was configured on '%s'\", namespace.load_balancer) else:", "== 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage", "'Standard' account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if", "i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix(", "\\ 'index {1} and vaultCertificate index {2} in arg {3}'", "namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher,", "def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd,", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import", "\"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\",", "zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x", "'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile:", "storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage", "is not False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to", "= 'new' logger.debug('new application gateway will be created') # AppGateway", "namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if", "namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk)", "= [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk,", "image type: {}'.format(image_type)) else: # did not specify image XOR", "as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg,", "'{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute',", "raise CLIError('Please specify password in non-interactive mode.') # validate password", "r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends", "CloudError validate_tags(namespace) try: # try capturing from VM, a most", "parts = t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else:", "id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from", "to existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return", "image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version =", "def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size = getattr(namespace,", "for output as logical name is more readable setattr(namespace, 'identity_role_id',", "if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY", "'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian',", "role, scope): import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client", "else win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if", "locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from", "def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id,", "= len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if", "secrets for use in VM Creation Secrets JSON structure [{", "'': namespace.public_ip_address_type = None logger.debug('no public IP address will be", "'new' logger.debug(\"specified storage account '%s' not found and will be", "Windows Server 2016, Windows Server 2012R2 publisher, offer, sku =", "CLIError(\"{}'s location can't be used to create the VM/VMSS because", "namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg,", "role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role", "2012R2 publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not", "configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified", "- check if a fully-qualified ID (assumes it is an", "100: err = \"'Standard' load balancer is required for scale-sets", "= 'usage error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI", "\"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept", "'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2',", "parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing", "'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif balancer_type", "ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if", "\"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\",", "= None source_disk = None source_snapshot = None if urlparse(source).scheme:", "NAME --resource-group NAME | --keyvault ID]') kv = namespace.keyvault rg", "the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2',", "not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if", "type for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from", "and namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones", "target resource group that matches the VM's location sku_tier =", "ValueError: pass if not role_id: # retrieve role id role_defs", "value should be a subrange of --vnet-address-prefix's\" # extract vnet", "'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple", "= \"'Standard' load balancer is required for scale-sets with 100+", "over_provision): mask = int(subnet_mask) # '2' are the reserved broadcasting", "elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned off", "will be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type =", "required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd,", "client.config.subscription_id, role) except ValueError: pass if not role_id: # retrieve", "if urlparse(source).scheme: # a uri? source_blob_uri = source elif '/disks/'", "msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import", "idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM", "process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error", "enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within vaultCertificates array", "(linux or windows) :return: errors if any were found :rtype:", "= _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb):", "'']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x", "== 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required,", "CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count", "out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask)", "2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd,", "= _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not", "\"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in", "= as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name,", "is not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in", "NIC will be created') return if not isinstance(nics_value, list): nics_value", "namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None:", "source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member", "be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id", "arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx,", "that matches the VM's location sku_tier = 'Premium' if 'Premium'", "elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS", "client.list(rg) if v.location == location and v.subnets): # 1 -", "if namespace.load_balancer is None and namespace.application_gateway is None: if std_lb_is_available:", "['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif", "x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint:", "== StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk',", "contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x", "username: raise CLIError(\"admin user name can not be empty\") is_linux", "namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability", "in VM Creation Secrets JSON structure [{ \"sourceVault\": { \"id\":", "[] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources:", "if namespace.platform_fault_domain_count is not None and namespace.zones is None: raise", "StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure Marketplace image'", "namespace.source: usage_error = 'usage error: --source {SNAPSHOT | DISK} |", "kv = namespace.keyvault rg = namespace.resource_group_name if rg: if not", "supplied to SSH Key Value. ' 'You can use --generate-ssh-keys", "import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys", "'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2',", "'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer',", "allowed when capturing \" \"images from virtual machines\") except CloudError:", "public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files", "if account: # 3 - nothing specified - find viable", "[--keyvault NAME --resource-group NAME | --keyvault ID]') kv = namespace.keyvault", "message = 'Secret is missing {0} within vaultCertificates array at", "specific storage profile # start with the required/forbidden parameters for", "use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace,", "value.\".format(username)) return username def _validate_admin_password(password, os_type): import re is_linux =", "namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will be", "an existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try:", "except ImportError: from urlparse import urlparse # pylint: disable=import-error from", "name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd,", "namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type is", "elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer", "required for zonal scale-sets\" elif namespace.instance_count > 100: err =", "'ssh_key_value'] # perform parameter validation for the specific storage profile", "\"value\", \"certificateStore\": \"cert store name (only on windows)\" }] }]", "elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type", "raise CLIError(\"usage error: '--single-placement-group' should be turned off for zonal", "role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd,", "compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for x in", "MIT License. See License.txt in the project root for license", "will be used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new'", "from vault name :param str vault_name: name of the key", "used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application", "ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory", "= re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in", "_validate_admin_password(password, os_type): import re is_linux = (os_type.lower() == 'linux') max_length", "= keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have", "'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4',", "' '--application-gateway NAME_OR_ID') # Resolve the type of balancer (if", "= [x for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if", "'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3',", "client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name", "public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public", "\"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None", "'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd,", "== StorageProfile.SACustomImage: return 'create unmanaged OS disk created from generalized", "get_subscription_id if is_valid_resource_id(val): return val kwargs = { 'name': val,", "in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find", "new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s", "logger.debug(\"specified public IP '%s' not found. It will be created.\",", "on the authentication type if namespace.authentication_type == 'password': if namespace.ssh_key_value", "elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type',", "if nothing specified, try to find an existing vnet and", "error: os type is required to create the image, \"", "as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities = [x", "'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg)", "VM, a most common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name,", "for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not", "namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not", "namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image =", "group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage", "containing secrets for use in VM Creation Secrets JSON structure", "\"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\",", "| --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path',", "from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile", "None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku", "- attempt to match an URN alias (most likely) from", "100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from", "resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk", "None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will be created')", "def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c,", "namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group',", "namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source", "namespace.instance_count, not namespace.disable_overprovision) result = next((s for s in vnet_match.subnets", "err = 'Secret is missing vaultCertificates array or it is", "image of '%s' failed for an error '%s'. Configuring plan", "namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace,", "subnet_is_id and not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet))", "if 'vaultCertificates' not in secret or not secret['vaultCertificates']: err =", "is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME |", "idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret", "be used to create the VM/VMSS because availablity zone is", "def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network',", "namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for i, _", "Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS", "namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd,", "Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is", "namespace.load_balancer is None and namespace.application_gateway is None: if std_lb_is_available: balancer_type", "[int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c,", "or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error: --assign-identity", "'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type =", "overflows? candidate_int = candidate_int - 2 # try the other", "gateway will be created') # AppGateway frontend required = []", "{1}'.format( idx, idx_arg)) if 'sourceVault' in secret and 'id' not", "try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass", "sku.lower() not in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid", "One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask =", "sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes", "if x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise", "- int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/')", "balancer_type, None) if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type))", "namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account)", "custom image' elif profile == StorageProfile.ManagedPirImage: return 'create managed OS", "namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None:", "Linux) by examining the OS type namespace.authentication_type = 'password' \\", "namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG will be", "\\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert", "# VMSS lacks some parameters, so scrub these out props_to_remove", "create a new storage account namespace.storage_account_type = 'new' logger.debug('no suitable", "determines what type is supplied for the --image parameter. Updates", "if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows?", "ImportError: from urlparse import urlparse # pylint: disable=import-error from knack.log", "assigned identity is only available under profile ' 'with minimum", "'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s',", "'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault':", "and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be used", "'%s' under because single placement group is disabled\", balancer_type) elif", "import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return", "pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin", ":param dict secrets: Dict fitting the JSON description above :param", "_get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None):", "a parsed JSON array containing secrets for use in VM", "for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions", "CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd,", "in secret: errors.append( 'Secret is missing sourceVault key at index", "list-skus' can be \" \"used to find such locations\".format(namespace.resource_group_name)) #", "StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk = _get_resource_id(", "compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '')", "'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo',", "type. Specify '--os-type' argument.\") if not namespace.authentication_type: # apply default", "bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID')", "name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks',", "'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk,", "can use --generate-ssh-keys to let CLI generate one for you')", "namespace.os_sku if not publisher: return publisher, offer, sku = publisher.lower(),", "namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in range(24, 16,", "SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian", "{k: v for k, v in kwargs.items() if not v}", "3 - nothing specified - find viable storage account in", "string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file", "namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName", "== 'linux') max_length = 72 if is_linux else 123 min_length", "scale-sets with 100+ instances\" else: err = \"'Standard' load balancer", "All rights reserved. # Licensed under the MIT License. See", "resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups',", "check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and", "namespace.public_ip_address_type = 'new' logger.debug('new public IP address will be created')", "if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [", "of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not in", "'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError(\"Subnet", "('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p, o, s in", "vnet) or (not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet'", "vm create --accelerated-networking --size Standard_DS1_v2' and # get it from", "if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if", "from Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach", "'create managed OS disk from custom image' elif profile ==", "return if not temp or not [x for x in", "will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id,", "distros = [('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel',", "== sku_tier and a.location == namespace.location), None) if account: #", "None: namespace.nsg_type = 'new' logger.debug('new NSG will be created') def", "return 'urn' # 5 - check if an existing managed", "and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only", "--subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists =", "= namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i in range(24,", "new_4core_sizes = [x.lower() for x in new_4core_sizes] if size not", "in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret is", "if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx,", "'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms',", "subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result =", "'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s',", "needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group", "for '{0}'. Create one first and try \" \"again.\".format(option_name)) return", "find a suitable existing vnet/subnet result = None if not", "= vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is", "if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else:", "subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type =", "secret in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append( 'Secret", "= \"More than one role matches the given name '{}'.", "'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2',", "pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name", "subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d =", "namespace.zones is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES')", "namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password)", "'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore',", "is None or size_info.number_of_cores < 8: return # VMs need", "int(subnet_mask) # '2' are the reserved broadcasting addresses # '*1.5'", "in nics_value: nics.append({ 'id': n if '/' in n else", "namespace.identity_role)) user_assigned_identities = [x for x in identities if x", "int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica count must", "_compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name'])", "image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged", "from msrestazure.tools import parse_resource_id # use minimal parameters to resolve", "or getattr(namespace, 'vm_sku', None) size = size.lower() # to refresh", "'%s' not found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address", "for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else:", "in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long", "not subnet and not nics: logger.debug('no subnet specified. Attempting to", "the type of balancer (if any) being used balancer_type =", "# 1 - check if a fully-qualified ID (assumes it", "= get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource", "# set default storage SKU if not provided and using", "it is empty at index {0} in ' \\ 'arg", "keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s' have been", "in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset will be", "the OS type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() ==", "will be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is", "try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s", "'Secret is missing sourceVault.id key at index {0} in arg", "msrestazure.tools import parse_resource_id # use minimal parameters to resolve the", "from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name,", "'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk']", "not namespace.authentication_type: # apply default auth type (password for Windows,", "validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if", "length must be between {} and {}'.format(min_length, max_length)) contains_lower =", "'{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No", "namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku", "are not exposed yet for VMSS, so use 'getattr' to", "for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower()", "in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage SKU", "case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with $", "as logical name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role,", "if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku =", "and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None:", "or re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if", "avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku,", "res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value", "'.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH", "--zones ZONES') if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group", "required, forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg =", "'{0}'. Create one first and try \" \"again.\".format(option_name)) return values[0]", "existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name,", "or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x", "vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location", "Resolve the type of balancer (if any) being used balancer_type", "namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources'", "'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet)", "# keep 'identity_role' for output as logical name is more", "size_info.number_of_cores < 8: return # VMs need to be a", "resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs =", "from generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged", "STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn':", "== namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer =", ">> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int =", "in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source)", "+ 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int:", "property if not hasattr(temp, 'location_info'): return if not temp or", "and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if", "k, v in kwargs.items() if not v} return resource_id(**kwargs) if", "msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in", "raise CLIError(linux_err if is_linux else win_err) if is_linux and re.findall(r'^[$-]+',", "CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id", "get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target resource group", "namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden", "is_linux = (os_type.lower() == 'linux') max_length = 72 if is_linux", "= getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized balancer", "(a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and", "namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error =", "storage account '%s' not found and will be created\", storage_id['name'])", "_validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "namespace.os_type: raise CLIError(\"usage error: os type is required to create", "must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions = regions_info #", "if not for_scale_set: result = next((s for s in vnet_match.subnets", "'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True)", "None logger.debug('no load balancer will be used') elif namespace.load_balancer is", "for secret in secrets] except Exception as err: raise CLIError('Error", "namespace.load_balancer_type = None logger.debug('no load balancer will be used') elif", "case character, 1 upper case character, 1 number and 1", "= 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name,", "'2' are the reserved broadcasting addresses # '*1.5' so we", "elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG will", "--source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try:", "and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and username.endswith('.'):", "'linux') max_length = 72 if is_linux else 123 min_length =", "vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value", "msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group", "namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates", "'vaultCertificates' not in secret or not secret['vaultCertificates']: err = 'Secret", "CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for", "here. logger.warning(\"No inbound nat pool was configured on '%s'\", namespace.load_balancer)", "not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location)", "frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity']", "(vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int", "'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2',", "Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name'", "except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found.", "get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id", "load balancer is required for scale-sets with 100+ instances\" else:", "CloudError: err = 'Invalid image \"{}\". Use a custom image", "resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n", "'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else", "if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or", "namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x", "'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC',", "namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name)", "os_type == 'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret)", "err = \"'Standard' load balancer is required for zonal scale-sets\"", "if not vnet and not subnet and not nics: logger.debug('no", "= load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images if", "disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image", "== LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load balancer is", "parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image']", "'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes] if size", "specified. Attempting to find an existing Vnet and subnet...') #", "is missing {0} within vaultCertificates array at secret ' \\", "existing vnet/subnet result = None if not for_scale_set: result =", "resolve OS type. Specify '--os-type' argument.\") if not namespace.authentication_type: #", "must be between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+',", "version of 2017-12-01') if namespace.identity_scope: if identities and MSI_LOCAL_ID not", "_validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() !=", "or key value must be supplied to SSH Key Value.", "== 'loadBalancer': # LoadBalancer frontend required = [] forbidden =", "start with the required/forbidden parameters for VM if namespace.storage_profile ==", "sizes if s.name.lower() == size), None) if size_info is None", "subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = []", "= 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name,", "'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required", "required for scale-sets with 100+ instances\" else: err = \"'Standard'", "namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5", "auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform", "['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo',", "balancer: application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend", "= False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be", "a suitable existing vnet/subnet result = None if not for_scale_set:", "--public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage", "\"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}'", "image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt", "'index {1} and vaultCertificate index {2} in arg {3}' if", "XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK')", "= len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info =", "re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type", "from custom image' elif profile == StorageProfile.ManagedPirImage: return 'create managed", "values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long", "== 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be used", "# 1 - find a suitable existing vnet/subnet result =", "logger.debug(\"suitable existing storage account '%s' will be used\", account.name) else:", "None and namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer'", "def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id", "the type for subsequent processing. \"\"\" from msrestazure.tools import is_valid_resource_id", "== StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom image'", "user_assigned_identities = [x for x in identities if x !=", "auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\",", "raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') #", "expected storage profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image:", "= None logger.debug('no load balancer will be used') elif namespace.load_balancer", "disk from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return", "subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks')", "StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name',", "warn here. logger.warning(\"No inbound nat pool was configured on '%s'\",", "namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i in", "namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and", "role matches the given name '{}'. Please pick an id", "snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk,", "= [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\",", "will be used\", account.name) else: # 4 - nothing specified", "4 - attempt to match an URN alias (most likely)", "if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku", "be used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new", "s in sizes if s.name.lower() == size), None) if size_info", "\"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\",", "disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk", "- check if an existing managed disk image resource compute_client", "a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location ==", "VM. VMSS has no such needs so far if getattr(namespace,", "if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise", "other way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) >", "[] namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources: for", "namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not", "'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public", "if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error: --license-type", "type is required to create the image, \" \"please specify", "is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\",", "subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2),", "'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile", "namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile =", "namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to", "namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage,", "= [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required,", "7.4, Windows Server 2016, Windows Server 2012R2 publisher, offer, sku", "CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version", "created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no", "'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new'", "None) if account: # 3 - nothing specified - find", "= _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info = compute_client.images.get(res['resource_group'],", "'%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s'", "subrange of --vnet-address-prefix's\" # extract vnet information needed to verify", "because single placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type", "import os try: from urllib.parse import urlparse except ImportError: from", "--size Standard_DS1_v2' and # get it from the error aval_sizes", "if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\", "'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3',", "get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx)", "name is more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif", "'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get(", "CLIError(\"admin user name can not be empty\") is_linux = (os_type.lower()", "is required because 'single placement group' is turned off\" raise", "IP address will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type", "return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic", "region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines", "None): image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri': #", "'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3',", "values: raise CLIError(\"No existing values found for '{0}'. Create one", "from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK)", "elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden =", "'storageAccounts'): # 1 - existing storage account specified namespace.storage_account_type =", "name (only on windows)\" }] }] :param dict secrets: Dict", "namespace.os_type: raise CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\")", "'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be used with", "_validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() !=", "vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will", "namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type", "not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at", "disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if", "is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and", "namespace.app_gateway_type = None logger.debug('no application gateway will be used') elif", "the reserved broadcasting addresses # '*1.5' so we have enough", "not provided and using an image based OS if not", "- subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int -", "None logger.debug('no public IP address will be used') elif namespace.public_ip_address", "resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def", "used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username", "_subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i < 16: err", "kernel # Oracle Linux 7.4, Windows Server 2016, Windows Server", "balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client", "resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic,", "get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name']", "subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID", "new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC',", "namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage", "provided and using an image based OS if not namespace.storage_sku", "return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx,", "process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if", "to resolve the expected storage profile if getattr(namespace, 'attach_os_disk', None)", "linux_err = r'admin user name cannot contain upper case character", "namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace):", "val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd,", "resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory", "uri? source_blob_uri = source elif '/disks/' in source.lower(): source_disk =", "namespace.storage_account_type = 'new' logger.debug('no suitable storage account found. One will", "'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo',", "{}' is not applicable as the '--scope' is not provided\".format(", "= None logger.debug('no NSG will be used') elif namespace.nsg is", "info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault =", "'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid image \"{}\".", "'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2',", "namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher", "TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd,", "'Standard_D14_v2', 'Standard_D5_v2_Promo', 'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms',", "import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if", "urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to match an", "namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def", "= parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK,", "== StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching',", "namespace.os_sku, image_version) # pylint: disable=no-member return image.plan except CloudError as", "marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS", "CloudError import re # 1 - check if a fully-qualified", "for x in aval_sizes] if size not in aval_sizes: return", "is None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]')", "getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size = size.lower()", "not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import", "['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set:", "= string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else:", "ids = [] if names_or_ids == [\"\"] or not names_or_ids:", "exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id for r", "= 'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account =", "subnet...') # if nothing specified, try to find an existing", "if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be", "== 'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows'", "not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group,", "= lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else:", "only be used when --public-ip-per-vm is enabled') if namespace.eviction_policy and", "if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if", "--image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type',", "Microsoft Corporation. All rights reserved. # Licensed under the MIT", "' \\ 'index {1} and vaultCertificate index {2} in arg", "raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values", "from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID", "> 1: ids = [r.id for r in role_defs] err", "single placement group is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value:", "namespace) if image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile", "STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE", "None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can", "\"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user name", "if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if", "= 'new' logger.debug('new NIC will be created') return if not", "cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error)", "in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos", "namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def", "= ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required =", "is None: size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku',", "elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden =", "'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2',", "required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if", "URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images =", "namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def", "'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo',", "for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image']", "< 3: raise CLIError('Password must have the 3 of the", "client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\", "if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os", "namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError:", "StorageProfile.SASpecializedOSDisk: return 'attach to existing unmanaged OS disk' elif profile", "namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet", "for t in namespace.target_regions: parts = t.split('=', 1) if len(parts)", "is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg))", "'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3',", "import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id", "re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise", "[x.name for x in balancer.backend_address_pools] if len(values) > 1: raise", "= 'new' logger.debug('new public IP address will be created') #", "balancer_type = 'None' if namespace.load_balancer is None and namespace.application_gateway is", "None) if not vnet and not subnet and not nics:", "bit_mask_len): a, b, c, d = [int(x) for x in", "'Secret is missing {0} within vaultCertificates array at secret '", "namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage error:", "2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not False else", "= [] for t in namespace.target_regions: parts = t.split('=', 1)", "idx, jdx, idx_arg)) if is_windows and 'certificateStore' not in cert:", "for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: # Associated scaleset", "raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params =", "CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source {SNAPSHOT", "_validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if", "in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if 'windows'", "os type is required to create the image, \" \"please", "_convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 -", "# a uri? source_blob_uri = source elif '/disks/' in source.lower():", "= getattr(namespace, 'application_security_groups') ids = [] if names_or_ids == [\"\"]", "== 'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported", "namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d in", "bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID", "# accept disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx,", "get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp =", "x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer", "if p.lower() == publisher and (o is None or o.lower()", "= image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn'", "number and 1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value", "subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if", "'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2',", "content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and '%s'", "return 'create unmanaged OS disk from Azure Marketplace image' elif", "namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway:", "re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new':", "profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def", "# extract additional information from a managed custom image res", "None logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile", "parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type =", "= cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage:", "--priority PRIORITY [--eviction-policy POLICY]') # endregion # region disk, snapshot,", "source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) # pylint:", "for s in sizes if s.name.lower() == size), None) if", "upper case character, 1 number and 1 special character') def", "{0} within vaultCertificates array at secret ' \\ 'index {1}", "if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type =", "v for k, v in kwargs.items() if not v} return", "raise CLIError(win_err) disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\",", "_parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type is supplied for", "ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise", "[x.lower() for x in aval_sizes] if size not in aval_sizes:", "errors.append(err.format(idx, idx_arg)) else: for jdx, cert in enumerate(secret['vaultCertificates']): message =", "from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util", "if namespace.generate_ssh_keys: # figure out appropriate file names: # 'base_name'(with", "for_scale_set: # VMSS lacks some parameters, so scrub these out", "' 'balancer or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd,", "else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile)", "'Standard_D14_v2_Promo', 'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3',", "'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set =", "{ 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription':", "vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len =", "gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend required =", "# get it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2',", "= nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx,", "on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx,", "namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type", "a.location == namespace.location), None) if account: # 3 - nothing", "def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username =", "'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for", "namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | '", "error: --vm-domain-name can only be used when --public-ip-per-vm is enabled')", "alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx)", "existing storage account '%s' will be used\", account.name) else: #", "NSG will be used') elif namespace.nsg is None: namespace.nsg_type =", "8: return # VMs need to be a supported image", "namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id", "gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'])", "is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not", "in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location == namespace.location),", "password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password)", "processing. \"\"\" from msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError", "_validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from", "VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) #", "from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx,", "['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif", "_get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id", "if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher =", "created') # AppGateway frontend required = [] if namespace.app_gateway_type ==", "https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace):", "'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes] if size", "'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage =", "= ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile", "See License.txt in the project root for license information. #", "= int(subnet_mask) # '2' are the reserved broadcasting addresses #", "needs so far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import", "been generated under ~/.ssh to \" \"allow SSH access to", "not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info", "contains_upper, contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if count", "< 16: err = \"instance count '{}' is out of", "\"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on windows)\" }]", "def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault')", "msrestazure.azure_exceptions import CloudError import re # 1 - check if", "if not missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return", "validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content =", "# '*1.5' so we have enough leeway for over-provision factor", "in client.list(rg) if v.location == location and v.subnets): # 1", "'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required", "mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int =", "will be used') elif namespace.nsg is None: namespace.nsg_type = 'new'", "GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK", "disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku", "'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC',", "failed for an error '%s'. Configuring plan settings \" \"will", "an error '%s'. Configuring plan settings \" \"will be skipped\",", "existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools", "namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx,", "'None' if namespace.load_balancer is None and namespace.application_gateway is None: if", "namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace):", "jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM Create", "('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re for p,", "from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find", "\"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on", "to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8],", "turned off for zonal scale-sets or with\" \" 100+ instances\")", "if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb", "description above :param string os_type: the type of OS (linux", "= 1.5 if over_provision else 1 return ((1 << (32", "nothing specified - create a new storage account namespace.storage_account_type =", "to create the image, \" \"please specify '--os-type OS_TYPE'\") def", "'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8',", "not supported for Windows VMs.') # validate proper arguments supplied", "process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error:", "compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or [])", "get it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo',", "'--application-gateway NAME_OR_ID') # Resolve the type of balancer (if any)", "PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4", "ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name =", "namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else:", "'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes", "'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs", "val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val))", "namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal parameters", "JSON structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{", "'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2',", "specify password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type)", "Windows VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage", "= _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk:", "else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image", "import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string", "# region disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk", "secrets: Dict fitting the JSON description above :param string os_type:", "and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create", "if size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo',", "namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name", "StorageProfile.ManagedCustomImage: return 'create managed OS disk from custom image' elif", "'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb',", "vaultCertificate index {2} in arg {3}' if 'certificateUrl' not in", "far if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName,", "'': namespace.app_gateway_type = None logger.debug('no application gateway will be used')", "import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else:", "or it is empty at index {0} in ' \\", "validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd,", "raise CLIError(\"usage error: {}'s replica count must be an integer\".format(parts[0]))", "or not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array", "cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with .' if", "params for new storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified", "error: '--single-placement-group' should be turned off for zonal scale-sets or", "attach_data_disks are not exposed yet for VMSS, so use 'getattr'", "def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for", "subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise", "72 if is_linux else 123 min_length = 12 if len(password)", "namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s' will be", "account '%s' will be used\", account.name) else: # 4 -", "'new' logger.debug('new application gateway will be created') # AppGateway frontend", "= 'loadBalancer' else: # needed for Stack profile 2017_03_09 balancer_type", "the status of required and forbidden parameters validate_parameter_set( namespace, required,", "get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id =", "2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg,", "std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku", "from azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics = []", "CLIError(\"This user name '{}' meets the general requirements, but is", "generated under ~/.ssh to \" \"allow SSH access to the", "image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries':", "in identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable when", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk =", "'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3',", "if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1])", "cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) #", "errors.append( 'Secret is missing sourceVault.id key at index {0} in", "cannot be used with SSH authentication type') validate_ssh_key(namespace) if not", "or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def", "= public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key", "> 100: if namespace.single_placement_group is None: namespace.single_placement_group = False elif", "100: if namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group:", "resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\",", "source) source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name, source)", "in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within vaultCertificates", "elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk from", "= namespace.nics nics = [] if not nics_value: namespace.nic_type =", "StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name',", "account '%s'\", storage_id['name']) else: # 2 - params for new", "# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "= _parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE PROFILE", "namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS'", "get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create Validators def", "= [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics", "forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num", "compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx,", "._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info:", "from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client =", "'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3',", "vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name:", "_get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product", "ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import uuid from", "at index {0} in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates'", "def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask = int(subnet_mask) # '2' are", "namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp", "= 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type =", "--license-type is only applicable on Windows VM scaleset') if not", "structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\":", "logger.debug('new NIC will be created') return if not isinstance(nics_value, list):", "names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network',", "likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched =", "_get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault name :param", ":rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "SKU if not provided and using an image based OS", "authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username)", "subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set", "process_remove_identity_namespace(cmd, namespace): if namespace.identities: from ._vm_utils import MSI_LOCAL_ID for i", "namespace.resource_group_name nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n,", "parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not", "mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh':", "namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower()", "urlparse except ImportError: from urlparse import urlparse # pylint: disable=import-error", "to resolve OS type. Specify '--os-type' argument.\") if not namespace.authentication_type:", "balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible values found", "characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err =", "ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client", "validate_parameter_set(namespace, required, forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg", "b, c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error:", "are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32", "type is supplied for the --image parameter. Updates the namespace", "= 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be used')", "'create unmanaged OS disk created from generalized VHD' elif profile", "that the status of required and forbidden parameters validate_parameter_set( namespace,", "namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS Create", "application gateway') elif balancer_type == 'loadBalancer': # LoadBalancer frontend required", "\"cert store name (only on windows)\" }] }] :param dict", "namespace.plan_publisher = image_plan.publisher return 'urn' # 3 - unmanaged vhd", "if 'sourceVault' not in secret: errors.append( 'Secret is missing sourceVault", "PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if", "== StorageProfile.ManagedSpecializedOSDisk: return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku):", "namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools", "from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id", "= get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name", "namespace.accelerated_networking is None: size = getattr(namespace, 'size', None) or getattr(namespace,", "from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from ._client_factory", "+ auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image',", "StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else", "= 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional information", "is missing vaultCertificates array or it is empty at index", "CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password',", "specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s' not found", "\\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id", "process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError", "parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id =", "storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'],", "or -' win_err = r'admin user name cannot contain special", "azure.cli.core.commands.client_factory import get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx,", "= '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24],", "t.split('=', 1) if len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count", "._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger = get_logger(__name__)", "namespace.storage_profile == StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk',", "namespace.image.lower()), None) if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer']", "'loadBalancer' else: # needed for Stack profile 2017_03_09 balancer_type =", "'location_info'): return if not temp or not [x for x", "from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach", "knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password =", "for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x]) #", "CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb GB') elif", "instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools", "image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images", "else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group,", "'is_default', None) is None: raise CLIError('usage error: --assign-identity [--scope SCOPE]", "namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will", "\" \"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements", "account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value", "or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if os.path.exists(string_or_file): logger.info('Use", "azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2'", "ssh/rdp, so warn here. logger.warning(\"No inbound nat pool was configured", "specified, try to find an existing vnet and subnet in", "'--os-type' argument.\") if not namespace.authentication_type: # apply default auth type", "disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx,", "target resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable", "'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in new_4core_sizes] if", "None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for i", "\" \"allow SSH access to the VM. If using machines", "= ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter", "CLIError(\"usage error: '--role {}' is not applicable as the '--scope'", "single placement group is disabled\", balancer_type) elif namespace.load_balancer: balancer_type =", "raise CLIError(\"usage error: os type is required to create the", "msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: #", "= image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower() ==", "\"\"\" Systematically determines what type is supplied for the --image", "= 'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name,", "exist.\".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet", "namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3", "names_or_ids == [\"\"] or not names_or_ids: return for val in", "1)[0] i = 0 for i in range(24, 16, -1):", "vnet_int: # overflows? candidate_int = candidate_int - 2 # try", "CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]') kv", "key value must be supplied to SSH Key Value. '", "and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for Windows", "re is_linux = (os_type.lower() == 'linux') max_length = 72 if", "created from generalized VHD' elif profile == StorageProfile.SAPirImage: return 'create", "create the image, \" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx,", "'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def", "subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id", "account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account '%s' will", "or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "if namespace.single_placement_group is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise", "image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos = [x for", "if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt to match", "'--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools:", "= StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type", "[x for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not", "'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i", "namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id from", "'%s' not found and will be created\", storage_id['name']) else: from", "used when --public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority:", "namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace):", "import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try", "get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name =", "# TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105 def", "error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile", "raise CLIError('SSH not supported for Windows VMs.') # validate proper", "= 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask", "elif balancer_type == 'loadBalancer': # LoadBalancer frontend required = []", "if namespace.os_version.lower() == 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer,", "CLIError(\"usage error: os type is required to create the image,", "None) size = size.lower() # to refresh the list, run", "sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account", "vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if", "'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC',", "try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if", "Fetch resource group from vault name :param str vault_name: name", "_get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\",", "any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd, namespace) if image_plan: namespace.plan_name", "subnet for vnet_match in (v for v in client.list(rg) if", "cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16],", "def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info if", "'{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def", "_validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils import list_sku_info if not", "defaults we are coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len", "id, or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for", "does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets',", "azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup',", "= parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return None", "disallowed_user_names = [ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\",", "count = len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char]", "under because single placement group is disabled\", balancer_type) elif namespace.load_balancer:", "be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None", "values found for '{0}'. Create one first and try \"", "'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret) for secret", "required: required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set default", "or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type", "!= 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden =", "None :rtype: str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4',", "raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int", "existing values found for '{0}'. Create one first and try", "= {k: v for k, v in kwargs.items() if not", "generate one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace,", "azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx,", "re for p, o, s in distros: if p.lower() ==", "gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if", "elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError('usage", "result = next((s for s in vnet_match.subnets if s.name.lower() !=", "namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if", "pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in", "attach-os-disk raise CLIError('incorrect usage: --image IMAGE | --attach-os-disk DISK') auth_params", "auth type (password for Windows, ssh for Linux) by examining", "None if not for_scale_set: result = next((s for s in", "in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if", "SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\", "# 5 - check if an existing managed disk image", "'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2',", "is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain", "elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new NSG will", "CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace):", "required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif", "= image_plan.publisher return 'urn' # 3 - unmanaged vhd based", "StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure Marketplace image'", "break if i < 16: err = \"instance count '{}'", "None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group'", "will be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type =", "idx_arg)) if is_windows and 'certificateStore' not in cert: errors.append(message.format('certificateStore', idx,", "replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions =", "namespace.image) if urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku", "when creating a new load ' 'balancer or application gateway", "'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC',", "int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg:", "matches the given name '{}'. Please pick an id from", "upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start with", "_validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not None:", "getattr(get_network_client(cli_ctx), balancer_type, None) if not client: raise CLIError('unrecognized balancer type:", "'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName',", "source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk", "None source_disk = None source_snapshot = None if urlparse(source).scheme: #", "is enabled') if namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error:", "id from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return", "or namespace.assign_identity is not None: identities = namespace.assign_identity or []", "missing vaultCertificates array or it is empty at index {0}", "namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if", "or (not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage:", "hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def", "role) except ValueError: pass if not role_id: # retrieve role", "except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) #", "source_blob_uri = source elif '/disks/' in source.lower(): source_disk = source", "Vnet and subnet...') # if nothing specified, try to find", "'.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s' and", "'.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private'", "unmanaged OS disk created from generalized VHD' elif profile ==", "raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv):", "'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3',", "namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and", "match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match:", "'^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'),", "Use a custom image name, id, or pick one from", "namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing", "the required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage: required", "'Invalid image \"{}\". Use a custom image name, id, or", "None) if size_info is None or size_info.number_of_cores < 8: return", "namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified", "namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve OS type.", "cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids =", "= 'new' logger.debug(\"specified storage account '%s' not found and will", "get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from", "else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku,", "Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to existing", "SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\", "\" \"will be skipped\", namespace.image, ex.message) # pylint: disable=inconsistent-return-statements def", "idx_arg)) if 'vaultCertificates' not in secret or not secret['vaultCertificates']: err", "= resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\", "existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing", "'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3',", "'%s' not found. It will be created.\", namespace.load_balancer) elif namespace.load_balancer", "2 # try the other way around if (candidate_int >>", "raise CLIError('An RSA key file or key value must be", "image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x:", "found. One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools", "--generate-ssh-keys to let CLI generate one for you') namespace.ssh_key_value =", "= [x for x in identities if x != MSI_LOCAL_ID]", "namespace.public_ip_address_type = None logger.debug('no public IP address will be used')", "elif namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd,", "NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s'", "'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif", "-1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i <", "be created') # Public-IP SKU is only exposed for VM.", "'{}' meets the general requirements, but is specifically disallowed for", "(only on windows)\" }] }] :param dict secrets: Dict fitting", "elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway'", "'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile ==", "2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if", "'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways')", "contains_special_char] if x]) # pylint: disable=line-too-long if count < 3:", "get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id from", "'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo',", "group that matches the VM's location sku_tier = 'Premium' if", "namespace and returns the type for subsequent processing. \"\"\" from", "getattr(namespace, 'vm_sku', None) size = size.lower() # to refresh the", "\"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\",", "by examining the OS type namespace.authentication_type = 'password' \\ if", "import re is_linux = (os_type.lower() == 'linux') max_length = 72", "in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len],", "found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '':", "'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type", "os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s', string_or_file) with", "not secret['vaultCertificates']: err = 'Secret is missing vaultCertificates array or", "namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please", "not exposed yet for VMSS, so use 'getattr' to avoid", "'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3',", "to \" \"allow SSH access to the VM. If using", "_convert_to_int(address, bit_mask_len): a, b, c, d = [int(x) for x", "\"More than one role matches the given name '{}'. Please", "not username: raise CLIError(\"admin user name can not be empty\")", "urn_match: namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3)", "values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from ._vm_utils", "on windows)\" }] }] :param dict secrets: Dict fitting the", "None or re.match(s, sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace):", "vnet and not subnet and not nics: logger.debug('no subnet specified.", "without \" \"permanent storage, back up your keys to a", "to '%s' under because single placement group is disabled\", balancer_type)", "if not isinstance(nics_value, list): nics_value = [nics_value] for n in", "in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret and", "can only be used when --public-ip-per-vm is enabled') if namespace.eviction_policy", "<< subnet_bit_mask_len) return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32],", "to find an existing Vnet and subnet...') # if nothing", "gateway will be used') elif namespace.application_gateway is None: namespace.app_gateway_type =", "the marketplace # Ubuntu 16.04, SLES 12 SP3, RHEL 7.4,", "is None: if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed", "if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using", "[\"\"] or not names_or_ids: return for val in names_or_ids: if", "namespace.storage_profile = StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: #", "will be created') # AppGateway frontend required = [] if", "# overflows? candidate_int = candidate_int - 2 # try the", "size = size.lower() # to refresh the list, run 'az", "\"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\",", "and 'id' not in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id", "namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None: raise", "if not client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer =", "disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err =", "[] if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot", "with a matching subnet for vnet_match in (v for v", "a new load ' 'balancer or application gateway frontend.') namespace.public_ip_address", "as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret", "ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace)", "def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not", "'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for", "get_logger from knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group,", "StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account',", "in props_to_remove: if prop in required: required.remove(prop) if prop in", "max_length + 1): raise CLIError('The password length must be between", "(candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) #", "'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name,", "content = f.read() elif not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure", "if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no", "not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type", "= public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content =", "_validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace)", "i < 16: err = \"instance count '{}' is out", "location and v.subnets): # 1 - find a suitable existing", "if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using", "if is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username): raise", "namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace)", "'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s',", "but is specifically disallowed for this image. Please try a", "d = [int(x) for x in address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a,", "(compute - 2017-03-30), Resource_sku doesn't implement location_info property if not", "is None: namespace.nsg_type = 'new' logger.debug('new NSG will be created')", "else 'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh':", "= _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id:", "candidate_int = candidate_int - 2 # try the other way", "in arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret", "_convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len))", "'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3',", "'{}'. Please pick an id from '{}'\" raise CLIError(err.format(role, ids))", "found. It will be created.\", namespace.nsg) elif namespace.nsg == '':", "Azure Marketplace image' elif profile == StorageProfile.SASpecializedOSDisk: return 'attach to", "for an error '%s'. Configuring plan settings \" \"will be", "CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools", "(r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name", "._vm_utils import normalize_disk_info # attach_data_disks are not exposed yet for", "count < 3: raise CLIError('Password must have the 3 of", "import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx))", "--resource-group NAME | --keyvault ID]') kv = namespace.keyvault rg =", "description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage:", "pylint: disable=import-error from knack.log import get_logger from knack.util import CLIError", "and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID |", "import azure.cli.core.keys as keys from ._client_factory import _compute_client_factory from ._actions", "new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d = [int(x)", "def _validate_admin_username(username, os_type): import re if not username: raise CLIError(\"admin", "value must be supplied to SSH Key Value. ' 'You", "# Associated scaleset will be missing ssh/rdp, so warn here.", "Key Value. ' 'You can use --generate-ssh-keys to let CLI", "and namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer' else:", "\"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info =", "False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result", "namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower()", "namespace.load_balancer_type = 'new' logger.debug('new load balancer will be created') if", "loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except Exception as", "elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id", "For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property", "# STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type ==", "logger.debug(\"specified storage account '%s' not found and will be created\",", "'Microsoft.ManagedIdentity') # TODO move to its own command module https://github.com/Azure/azure-cli/issues/5105", "VM Creation Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\"", "\"certificateStore\": \"cert store name (only on windows)\" }] }] :param", "nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will", "123 min_length = 12 if len(password) not in range(min_length, max_length", "None: if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for", "group name or None :rtype: str \"\"\" from azure.cli.core.profiles import", "application gateway will be used') elif namespace.application_gateway is None: namespace.app_gateway_type", "[x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}':", "to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if", "n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary':", "not keys.is_valid_ssh_rsa_public_key(content): if namespace.generate_ssh_keys: # figure out appropriate file names:", "no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos,", "azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx))", "= StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk", "getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod =", "supported image in the marketplace # Ubuntu 16.04, SLES 12", "get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group that matches", "specified availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from", "forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required =", "are the reserved broadcasting addresses # '*1.5' so we have", "# pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return", "size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location)", "--disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import", "1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError: raise", "StorageProfile.ManagedCustomImage: # extract additional information from a managed custom image", "1 - existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using", "{1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for", "3 of the following: 1 lower case character, 1 upper", "'az vm list-skus' can be \" \"used to find such", "elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk'] forbidden", "refresh the list, run 'az vm create --accelerated-networking --size Standard_DS1_v2'", "'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2',", "image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']:", "keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath =", "Create one first and try \" \"again.\".format(option_name)) return values[0] def", "cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use", "16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break if i", "content = string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key", "not namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else", "'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes =", "= None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else:", "namespace.application_gateway is None: if std_lb_is_available: balancer_type = 'loadBalancer' else: #", "-' win_err = r'admin user name cannot contain special characters", "# attach_data_disks are not exposed yet for VMSS, so use", "else: # needed for Stack profile 2017_03_09 balancer_type = 'loadBalancer'", "--vm-domain-name can only be used when --public-ip-per-vm is enabled') if", "def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is", "if std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for Stack", "def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client =", "'%s' have been generated under ~/.ssh to \" \"allow SSH", "case character, 1 number and 1 special character') def validate_ssh_key(namespace):", "frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from", "import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account", "if namespace.accelerated_networking is None: size = getattr(namespace, 'size', None) or", "in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': {", "# use minimal parameters to resolve the expected storage profile", "_validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array containing secrets", "supplied based on the authentication type if namespace.authentication_type == 'password':", "from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.commands.client_factory import get_subscription_id if", "= matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5 -", "knack.log import get_logger from knack.util import CLIError from azure.cli.core.commands.validators import", "an existing Vnet and subnet...') # if nothing specified, try", "> int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is", "not publisher: return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower()", "= 'password' \\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else", "If using machines without \" \"permanent storage, back up your", "* factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size", "in vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet", "additional information from a managed custom image res = parse_resource_id(namespace.image)", "MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user", "val in names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id,", "cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer", "vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not", "is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val )", "'windows' and namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk:", "namespace): if namespace.accelerated_networking is None: size = getattr(namespace, 'size', None)", "except ValueError: pass if not role_id: # retrieve role id", "if identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error:", "compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for", "OS disk created from generalized VHD' elif profile == StorageProfile.SAPirImage:", "Secrets JSON structure [{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\":", "location can't be used to create the VM/VMSS because availablity", "if namespace.data_disk_sources: for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot =", "and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role' is", "balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if", "'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for", "else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0]", "'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower() for", "_get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed", "extract additional information from a managed custom image res =", "from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if", "== StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure Marketplace", "'{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role)) elif", "if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and std_lb_is_available:", "namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if", "gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage", "# STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized", "_compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images',", "= namespace.assign_identity or [] from ._vm_utils import MSI_LOCAL_ID for i,", "RSA key file or key value must be supplied to", "CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set:", "One will be created.') def _validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import", "is required to create the image, \" \"please specify '--os-type", "namespace.location nics = getattr(namespace, 'nics', None) if not vnet and", "ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def", "namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk", "application gateway will be created') # AppGateway frontend required =", "return publisher, offer, sku = publisher.lower(), offer.lower(), sku.lower() distros =", "rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account specified", "= list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in sku_infos", "{}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks", "<< (32 - mask)) - 2) > int(vmss_instance_count * factor)", "# endregion # region disk, snapshot, image validators def validate_vm_disk(cmd,", "password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char", "{ \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert", "not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource", "secret in secrets] except Exception as err: raise CLIError('Error decoding", "VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name =", "except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id return", "= 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace,", "forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network", "between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper", "namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if", "more readable setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or", "--disk EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk) !=", "# if nothing specified, try to find an existing vnet", "_validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk'] forbidden", "CLIError('usage error: user assigned identity is only available under profile", "name of the key vault :return: resource group name or", "elif not lb.inbound_nat_pools: # Associated scaleset will be missing ssh/rdp,", "file or key value must be supplied to SSH Key", "# try capturing from VM, a most common scenario res_id", "explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in", "namespace.os_version = matched['version'] return 'urn' # 5 - check if", "CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( #", "list): nics_value = [nics_value] for n in nics_value: nics.append({ 'id':", "not specify image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE", "'authentication_type', 'generate_ssh_keys', 'ssh_dest_key_path', 'ssh_key_value'] # perform parameter validation for the", "required to create the image, \" \"please specify '--os-type OS_TYPE'\")", "== 'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num", "(subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise", "16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux,", "'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3',", "'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own command module", "namespace.app_gateway_type = 'new' logger.debug('new application gateway will be created') #", "import urlparse except ImportError: from urlparse import urlparse # pylint:", "name '{}' meets the general requirements, but is specifically disallowed", "s in vnet_match.subnets if _check_subnet(s)), None) if not result: continue", "ex: logger.warning(\"Querying the image of '%s' failed for an error", "namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\",", "only be used when creating a new load ' 'balancer", "'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not", "def validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import", "default auth type (password for Windows, ssh for Linux) by", "arguments supplied based on the authentication type if namespace.authentication_type ==", "else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info =", "required because 'single placement group' is turned off\" raise CLIError('usage", "command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def", "not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2',", "'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is", "errors if any were found :rtype: list \"\"\" is_windows =", "role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs: raise", "namespace.ultra_ssd_enabled = True # Now verify that the status of", "required.remove(prop) if prop in forbidden: forbidden.remove(prop) # set default storage", "nics: logger.debug('no subnet specified. Attempting to find an existing Vnet", "from msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage", "'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets,", "'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri':", "= 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku)", "win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not", "namespace.instance_count > 100: err = \"'Standard' load balancer is required", "namespace.disable_overprovision): break if i < 16: err = \"instance count", "is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re # 1 -", "'/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if not role_id: #", "to specify a capable one. 'az vm list-skus' can be", "used balancer_type = 'None' if namespace.load_balancer is None and namespace.application_gateway", "existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load", "existing vnet and subnet in the target resource group client", "not for_scale_set: result = next((s for s in vnet_match.subnets if", "address.split('.')] result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2)", "> 100: err = \"'Standard' load balancer is required for", "c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix", "address will be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type =", "namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer, sku =", "above :param string os_type: the type of OS (linux or", "or windows) :return: errors if any were found :rtype: list", "CLIError('\\n'.join(errors)) # region VM Create Validators def _parse_image_argument(cmd, namespace): \"\"\"", "name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from", "namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]:", "storage account '%s' will be used\", account.name) else: # 4", "not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no latest", "names: # 'base_name'(with private keys), and 'base_name.pub'(with public keys) public_key_filepath", "disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id", "raise CLIError('usage error: --license-type is only applicable on Windows VM", "public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath,", "r in role_defs] err = \"More than one role matches", "if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd,", "uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except ValueError: pass if", "= get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name =", "License. See License.txt in the project root for license information.", "have been generated under ~/.ssh to \" \"allow SSH access", "def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client", "ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx)", "# Ubuntu 16.04, SLES 12 SP3, RHEL 7.4, CentOS 7.4,", "It will be created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type", "CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx,", "msrestazure.azure_exceptions import CloudError validate_tags(namespace) try: # try capturing from VM,", "'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows", "error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri)", "raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace):", "# STORAGE PROFILE #3 namespace.storage_profile = StorageProfile.SASpecializedOSDisk else: # STORAGE", "storage SKU if not provided and using an image based", "to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []),", "password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for", "lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if", "CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: # 2 -", "namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product,", "std_lb_is_available: balancer_type = 'loadBalancer' else: # needed for Stack profile", "get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k, v in", "not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise", "if not provided and using an image based OS if", "def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name,", "frontend required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity')", "else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num =", "1: raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}'", "_validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type is None:", "vm list-skus' can be \" \"used to find such locations\".format(namespace.resource_group_name))", "None) is None: raise CLIError(\"usage error: '--role {}' is not", "logger.debug('no load balancer will be used') elif namespace.load_balancer is None:", "import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group = namespace.resource_group_name subscription_id", "\"--subnet SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg,", "namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace,", "namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion", "_get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image", "validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd,", "sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher,", "for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ',", "{1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise", "from urllib.parse import urlparse except ImportError: from urlparse import urlparse", "'%s' will be used\", account.name) else: # 4 - nothing", "in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace,", "specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG", "'/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties':", "None: raise CLIError(\"usage error: '--role {}' is not applicable as", "replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica", "scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in", "import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name", "image' elif profile == StorageProfile.ManagedPirImage: return 'create managed OS disk", "if zone_info: sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for", "not namespace.os_type: raise CLIError(\"usage error: os type is required to", "key at index {0} in arg {1}'.format( idx, idx_arg)) if", "= \"usage error: --subnet-address-prefix value should be a subrange of", "and subnet in the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks", "publisher and (o is None or o.lower() == offer) and", "STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not", "parameters, so scrub these out props_to_remove = ['attach_os_disk', 'storage_account'] for", "+ '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH key files '%s'", "elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1", "size_info is None or size_info.number_of_cores < 8: return # VMs", "image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage", "\"Stretch\" with backports kernel # Oracle Linux 7.4, Windows Server", "| DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk,", "created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import", "_get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope and getattr(namespace.identity_role,", "not in cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and", "= ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account',", "if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix,", "= getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size =", "the expected storage profile if getattr(namespace, 'attach_os_disk', None) and not", "- mask)) - 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx,", "3 - unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri'", "namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as single placement group", "be turned off for zonal scale-sets or with\" \" 100+", "VM/VMSS because availablity zone is not yet \" \"supported. Please", "storage_id['name']) else: # 2 - params for new storage account", "ssh for Linux) by examining the OS type namespace.authentication_type =", "_validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace)", "parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps", "{0} in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else:", "usage: --image IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username',", "= ['os_type', 'attach_os_disk', 'storage_account', 'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku)", "validate_parameter_set(namespace, required, forbidden, description='network balancer: application gateway') elif balancer_type ==", "in ' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for", "# start with the required/forbidden parameters for VM if namespace.storage_profile", "It will be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type", "# pylint: disable=import-error from knack.log import get_logger from knack.util import", "return for val in names_or_ids: if not is_valid_resource_id(val): val =", "public IP address will be created') # Public-IP SKU is", "is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will be", "error: --license-type is only applicable on Windows VM scaleset') if", "#6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk',", "'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku']", "== offer) and (s is None or re.match(s, sku, re.I)):", "_ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx,", "namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk", "len(image_info.storage_profile.data_disks or []) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'],", "'SQLGLCore', 'Standard_D4_v3', 'Standard_D4s_v3', 'Standard_D2_v2', 'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2',", "'new' logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if", "raise CLIError('Password must have the 3 of the following: 1", "is only available under profile ' 'with minimum Compute API", "_resolve_role_id(cli_ctx, role, scope): import re import uuid from azure.cli.core.commands.client_factory import", "scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from", "for x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos:", "process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities:", "user name '{}' meets the general requirements, but is specifically", "VM's location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else", "[{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only on windows)\"", "ID]') kv = namespace.keyvault rg = namespace.resource_group_name if rg: if", "namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to", "namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not found. It", "namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage error:", "VM scaleset') if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error:", "v.subnets): # 1 - find a suitable existing vnet/subnet result", "namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg", "= IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and", "_validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones is None:", "resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability", "[] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type !=", "'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage", "image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:", "this image. Please try a different value.\".format(username)) return username def", "_validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and", "CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from", "client.get(resource_group, balancer_name) values = [x.name for x in balancer.backend_address_pools] if", "_get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err", "suitable storage account found. One will be created.') def _validate_vm_create_availability_set(cmd,", "parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or", "# LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway',", "else: if kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx,", "validate_tags(namespace) try: # try capturing from VM, a most common", "'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version", "from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet", "publisher, offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher:", "or start with $ or -' win_err = r'admin user", "the list, run 'az vm create --accelerated-networking --size Standard_DS1_v2' and", "= r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@# or", "if os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s', string_or_file)", "from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group =", "if not namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower()", "not subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists:", "virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name,", "namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks =", "else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint:", "lower case character, 1 upper case character, 1 number and", "if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups',", "from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if", "name, id, or pick one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias']", "size.lower() # to refresh the list, run 'az vm create", "from ._vm_utils import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i]", "if namespace.target_regions: regions_info = [] for t in namespace.target_regions: parts", "the type of OS (linux or windows) :return: errors if", "'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3',", "for Stack profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is", "error: {}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count))", "or o.lower() == offer) and (s is None or re.match(s,", "= ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku)", "'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage", "import CloudError import re # 1 - check if a", "urlparse(source).scheme: # a uri? source_blob_uri = source elif '/disks/' in", "if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled", "it is an image ID) if is_valid_resource_id(namespace.image): return 'image_id' #", "= ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer:", "raise CLIError('There is no latest image version exists for \"{}\"'.format(namespace.image))", "try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError:", "from ._vm_utils import normalize_disk_info # attach_data_disks are not exposed yet", "namespace): from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if", "ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts #", "\"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\",", "'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type", "load balancer will be created') if namespace.load_balancer_type == 'new' and", "= (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content = string_or_file if", "lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type", "based on the authentication type if namespace.authentication_type == 'password': if", "import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts", "be created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None", "# figure out appropriate file names: # 'base_name'(with private keys),", "if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return", "account namespace.storage_account_type = 'new' logger.debug('no suitable storage account found. One", "new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name,", "namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg, lb_name, 'load_balancers') if not namespace.nat_pool_name:", "try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets] except Exception", "# pylint:disable=too-many-lines import os try: from urllib.parse import urlparse except", "sku as single placement group is turned off\") elif namespace.load_balancer_sku", "namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from", "namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix is None: namespace.app_gateway_subnet_address_prefix = _get_next_subnet_addr_suffix( namespace.vnet_address_prefix, namespace.subnet_address_prefix,", "CLIError(\"Unable to resolve OS type. Specify '--os-type' argument.\") if not", "= role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role)", "ValueError('Admin password cannot be used with SSH authentication type') validate_ssh_key(namespace)", "'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS',", "only available under profile ' 'with minimum Compute API version", "idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region VM Create Validators", "props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop", "'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() == '.pub':", "storage account '%s'\", storage_id['name']) else: # 2 - params for", "not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group, namespace='Microsoft.Network', type='applicationSecurityGroups', name=val", "offer) and (s is None or re.match(s, sku, re.I)): namespace.accelerated_networking", "type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path = \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def", "and forbidden parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile)))", "logger.warning(\"SSH key files '%s' and '%s' have been generated under", "for zonal scale-sets\" elif namespace.instance_count > 100: err = \"'Standard'", "subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type =", "= None if not for_scale_set: result = next((s for s", "'%s' not found. It will be created.\", namespace.nsg) elif namespace.nsg", "raise CLIError('--public-ip-address can only be used when creating a new", "is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i = 0 for", "namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd,", "elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type == 'applicationGateway': if", "CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found. It", "find an existing Vnet and subnet...') # if nothing specified,", "required, forbidden, description='network balancer: application gateway') elif balancer_type == 'loadBalancer':", "return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable", "resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set)", "== '': namespace.app_gateway_type = None logger.debug('no application gateway will be", "'identity_role' for output as logical name is more readable setattr(namespace,", "from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def", "accept disk name or ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk,", "created') return if not isinstance(nics_value, list): nics_value = [nics_value] for", "namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only be", "cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t in namespace.target_regions:", "1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'),", "', confirm=True) except NoTTYException: raise CLIError('Please specify password in non-interactive", "from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id =", "your keys to a safe location.\", private_key_filepath, public_key_filepath) else: raise", "the image of '%s' failed for an error '%s'. Configuring", "COUNT --zones ZONES') if namespace.zones or namespace.instance_count > 100: if", "\" \"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from", "== 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count,", "source elif '/snapshots/' in source.lower(): source_snapshot = source else: compute_client", "= 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg)", "!= bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def", "account in target resource group namespace.storage_account = account.name namespace.storage_account_type =", "None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from", "'existing' logger.debug(\"suitable existing storage account '%s' will be used\", account.name)", "cert: errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore' not", "logger.debug(\"existing vnet '%s' and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return", "role_defs] err = \"More than one role matches the given", "addresses # '*1.5' so we have enough leeway for over-provision", "not names_or_ids: return for val in names_or_ids: if not is_valid_resource_id(val):", "'certificateStore' not in cert: errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors:", "# pylint: disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying", "= StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage", "['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else:", "'size', None) or getattr(namespace, 'vm_sku', None) size = size.lower() #", "and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is", "PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image type:", "Compute API version of 2017-12-01') if namespace.identity_scope: if identities and", "{}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions", "'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type", "'': namespace.nsg_type = None logger.debug('no NSG will be used') elif", "array at secret ' \\ 'index {1} and vaultCertificate index", "compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info =", "urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name,", "= 'new' logger.debug(\"load balancer '%s' not found. It will be", "'existing' logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type", "( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from", "CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not specify image", "and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+',", "'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage", "lb_name) if lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or", "it from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo',", "- attempt to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)',", "# pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set else 'Premium_LRS'", "disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type", "True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is", "'publicIPAddresses'): namespace.public_ip_address_type = 'existing' logger.debug(\"using existing specified public IP '%s'\",", "raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret):", "lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type = 'existing'", "OS type. Specify '--os-type' argument.\") if not namespace.authentication_type: # apply", "resource_id from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute',", "over_provision else 1 return ((1 << (32 - mask)) -", "is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not", "from ._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace):", "if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except", "empty at index {0} in ' \\ 'arg {1} '", "'--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError", "if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else:", "VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets', vnet,", "broadcasting addresses # '*1.5' so we have enough leeway for", "'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2',", "re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x", "= info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk =", "namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx, rg,", "not in identities: raise CLIError(\"usage error: '--scope'/'--role' is only applicable", "== 'new' and namespace.single_placement_group is False and std_lb_is_available: LBSkuName =", "[]) else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) #", "in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try:", "res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type =", "= (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+'", "_get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key:", "x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError", "== 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True #", "turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import", "storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client", "'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2',", "not allowed when capturing \" \"images from virtual machines\") except", "= get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if", "not yet \" \"supported. Please use '--location' to specify a", "[] if not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will", "or []) else: raise CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image))", "setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role, namespace.identity_scope)) elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default',", "forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params", "of '%s' failed for an error '%s'. Configuring plan settings", "username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}' meets the", "managed OS disk from Azure Marketplace image' elif profile ==", "== StorageProfile.ManagedPirImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk', 'storage_account',", "allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info): from", "try the other way around if (candidate_int >> (vnet_bit_mask_len -", "account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account", "IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP", "be between {} and {}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password)", "namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace)", "source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info", "mask = int(subnet_mask) # '2' are the reserved broadcasting addresses", "if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg =", "compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or [])", ">> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format", "specified existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type =", "will be missing ssh/rdp, so warn here. logger.warning(\"No inbound nat", "resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try:", "info.id except CloudError: info = compute_client.disks.get(resource_group_name, source) source_disk = info.id", "in aval_sizes] if size not in aval_sizes: return new_4core_sizes =", "'images', 'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid image", "'/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not username: raise", "should be turned off for zonal scale-sets or with\" \"", "> vnet_int: # overflows? candidate_int = candidate_int - 2 #", "namespace.image and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace)", "win_err = r'admin user name cannot contain special characters \\/\"[]:|<>+=;,?*@#", "import parse_resource_id # use minimal parameters to resolve the expected", "Attempting to find an existing Vnet and subnet...') # if", "--vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network', 'subnets',", "_validate_admin_username(username, os_type): import re if not username: raise CLIError(\"admin user", "load balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer", "namespace.eviction_policy and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy", "if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError( \"incorrect usage for authentication-type", "SSH Key Value. ' 'You can use --generate-ssh-keys to let", "client: raise CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name)", "applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage =", "dict secrets: Dict fitting the JSON description above :param string", "storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage account found.", "NoTTYException: raise CLIError('Please specify password in non-interactive mode.') # validate", "namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion #", "subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type", "= 'new' logger.debug('new load balancer will be created') if namespace.load_balancer_type", "# pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if", "[--role ROLE]') def _resolve_role_id(cli_ctx, role, scope): import re import uuid", "the other way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len))", "not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is only", "None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will be created')", "namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/',", "created.\", namespace.load_balancer) elif namespace.load_balancer == '': namespace.load_balancer_type = None logger.debug('no", "False else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under", "# validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if", "None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when", "get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id) if", "'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage", "project root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import", "else 123 min_length = 12 if len(password) not in range(min_length,", "'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2',", "existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type = 'new'", "raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or", "logger.debug('new NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg:", "private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath) logger.warning(\"SSH", "= int(parts[1]) except ValueError: raise CLIError(\"usage error: {}'s replica count", "is an image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2", "JSON description above :param string os_type: the type of OS", "a custom image name, id, or pick one from {}'", "# perform parameter validation for the specific storage profile #", "rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic", "logger.debug('existing NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in", "image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE #1 namespace.storage_profile", "CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is", "Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client", "under the MIT License. See License.txt in the project root", "None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'),", "_validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace)", "Now verify that the status of required and forbidden parameters", "= urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan = _get_image_plan_info_if_exists(cmd,", "an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image) if urn_match: namespace.os_publisher", "namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx,", "is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to match an", "common scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res", "not temp or not [x for x in (temp.location_info or", "2017-03-30), Resource_sku doesn't implement location_info property if not hasattr(temp, 'location_info'):", "will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg =", "using machines without \" \"permanent storage, back up your keys", "location = namespace.location nics = getattr(namespace, 'nics', None) if not", "namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if", "'') if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'],", "namespace.identity_scope: if identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage", "namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb =", "= _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version", "\" \"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot", "nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg))", "must have the 3 of the following: 1 lower case", "import get_logger from knack.util import CLIError from azure.cli.core.commands.validators import (", "SSH public key file: %s', string_or_file) with open(string_or_file, 'r') as", "check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage", "o.lower() == offer) and (s is None or re.match(s, sku,", "namespace.os_publisher, namespace.os_offer, namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location,", "from a managed custom image res = parse_resource_id(namespace.image) compute_client =", "urlparse import urlparse # pylint: disable=import-error from knack.log import get_logger", "try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest': image_version =", "if matched: namespace.os_publisher = matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku =", "OS disk from custom image' elif profile == StorageProfile.ManagedPirImage: return", "if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set", "_validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username,", "from azure.cli.core.commands.client_factory import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines',", "= { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type,", "latest image version exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda", "for vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] ==", "lacks some parameters, so scrub these out props_to_remove = ['attach_os_disk',", "x in aval_sizes] if size not in aval_sizes: return new_4core_sizes", "if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address, namespace.resource_group_name, 'Microsoft.Network', 'publicIPAddresses'): namespace.public_ip_address_type =", "keys from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version logger", "CLIError('unrecognized balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values =", "of --vnet-address-prefix's\" # extract vnet information needed to verify the", "perform parameter validation for the specific storage profile # start", "'images': image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num =", "namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import CloudError validate_tags(namespace)", "rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage', 'storageAccounts'):", "sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'],", "len(password) not in range(min_length, max_length + 1): raise CLIError('The password", "return 'attach existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus =", "string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key file: %s',", "if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info", "for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows'", "_get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk", "exists for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else:", "import get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name']", "'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2', 'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s',", "balancer_type == 'loadBalancer': # LoadBalancer frontend required = [] forbidden", "does not exist.\".format(subnet)) elif subnet_exists: # 2 - user specified", "authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import", "import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools", "= parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images':", "existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create", "('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer',", "namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace)", "off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType", "let CLI generate one for you') namespace.ssh_key_value = content def", "namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error: os type is", "import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg =", "'%s' and '%s' have been generated under ~/.ssh to \"", "'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2',", "if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned", "_validate_vm_vmss_msi(cmd, namespace) if namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion", "logger.debug(\"using specified vnet '%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return", "and vnet) or (not subnet_is_id and not vnet): raise CLIError(\"incorrect", "image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3 - unmanaged", "storage account specified namespace.storage_account_type = 'new' logger.debug(\"specified storage account '%s'", "namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace)", "'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC',", "elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP", "'Standard_DS2_v2', 'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes", "raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from", "< 8: return # VMs need to be a supported", "from msrestazure.azure_exceptions import CloudError import re # 1 - check", "'primary': nics_value[0] == n } }) namespace.nics = nics namespace.nic_type", "azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage", "[]) if x.zones]: raise CLIError(\"{}'s location can't be used to", "logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some", "_validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd,", "Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info property if", "= compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return", "= \\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not", "an id from '{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id", "parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower() == 'images': image_info", "= nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s)", "raise CLIError(usage_error) def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from", "CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion # region", "'id': n if '/' in n else resource_id(name=n, resource_group=namespace.resource_group_name, namespace='Microsoft.Network',", "type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8))", "namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters, so scrub", "if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'],", "('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ',", "'{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg = \"usage", "namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = []", "ZONES') if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is", "= s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s", "rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name)", "in source.lower(): source_snapshot = source else: compute_client = _compute_client_factory(cli_ctx) #", "== 'windows' errors = [] try: loaded_secret = [validate_file_or_dict(secret) for", "be used when creating a new load ' 'balancer or", "compute_client.snapshots.get(resource_group_name, source) source_snapshot = info.id except CloudError: info = compute_client.disks.get(resource_group_name,", "verify the defaults we are coming out vnet_ip_address, mask =", "'sourceVault' in secret and 'id' not in secret['sourceVault']: errors.append( 'Secret", "def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use", "subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len:", "raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format(", "be used') elif namespace.load_balancer is None: namespace.load_balancer_type = 'new' logger.debug('new", "leeway for over-provision factor = 1.5 if over_provision else 1", "azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name,", "_compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source) source_snapshot", "\" \"permanent storage, back up your keys to a safe", "= source elif '/snapshots/' in source.lower(): source_snapshot = source else:", "err = \"More than one role matches the given name", "IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None and namespace.app_gateway_type", "and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku =", "not found. It will be created.\", namespace.public_ip_address) elif namespace.public_ip_address ==", "= get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None", "given name '{}'. Please pick an id from '{}'\" raise", "found :rtype: list \"\"\" is_windows = os_type == 'windows' errors", "'' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id", "import CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType", "offer, sku = publisher.lower(), offer.lower(), sku.lower() distros = [('canonical', 'UbuntuServer',", "special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh',", "be a supported image in the marketplace # Ubuntu 16.04,", "None if urlparse(source).scheme: # a uri? source_blob_uri = source elif", "'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2',", "VMSS lacks some parameters, so scrub these out props_to_remove =", "'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx)", "will be used') elif namespace.application_gateway is None: namespace.app_gateway_type = 'new'", "get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if names_or_ids", "the VM's location with a matching subnet for vnet_match in", "in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return", "= ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer: application", "matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version']", "subnet and not nics: logger.debug('no subnet specified. Attempting to find", "is None: namespace.load_balancer_type = 'new' logger.debug('new load balancer will be", "= os_type == 'windows' errors = [] try: loaded_secret =", "if x.name.lower() == size_info.lower()), None) # For Stack (compute -", "to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd,", "try a different value.\".format(username)) return username def _validate_admin_password(password, os_type): import", "or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx,", "too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id #", "as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name)", "'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3', 'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3',", "12 if len(password) not in range(min_length, max_length + 1): raise", "be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None", "will be created') # Public-IP SKU is only exposed for", "vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet", "id_comps = parse_resource_id(vault.id) if id_comps['name'] == vault_name: return id_comps['resource_group'] return", "- 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if", "namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is None", "be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "ValueError( \"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password", "'vm_sku', None) size = size.lower() # to refresh the list,", "implement location_info property if not hasattr(temp, 'location_info'): return if not", "namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed", "namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect", "as keys from ._client_factory import _compute_client_factory from ._actions import _get_latest_image_version", "if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage: required =", "['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop in required:", "some parameters, so scrub these out props_to_remove = ['attach_os_disk', 'storage_account']", "source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage", "int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address,", "None: size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None)", "PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace):", "get_mgmt_service_client storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in", "OS disk from Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk:", "!= 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet':", "return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace):", "raise CLIError(\"usage error: '--role {}' is not applicable as the", "if a fully-qualified ID (assumes it is an image ID)", "\"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\",", "is None and namespace.application_gateway is None: if std_lb_is_available: balancer_type =", "not in range(min_length, max_length + 1): raise CLIError('The password length", "a supported image in the marketplace # Ubuntu 16.04, SLES", "and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error: '--role", "from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME", "if an existing managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx)", "= 'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client =", "if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to match", "with .' if re.findall(pattern, username): raise CLIError(linux_err if is_linux else", "{}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd,", "for data_disk_source in namespace.data_disk_sources: source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx,", "pass if not role_id: # retrieve role id role_defs =", "azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from", "and subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id", "namespace='Microsoft.Network', type='networkInterfaces', subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n }", "identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not namespace.identity_scope", "{SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri,", "id_comps['name'] == vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val,", "== '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath +", "= _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to", "is specifically disallowed for this image. Please try a different", "namespace.authentication_type == 'ssh': raise CLIError('SSH not supported for Windows VMs.')", "profile if getattr(namespace, 'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk:", "will be created.\", namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type =", "missing_kwargs = {k: v for k, v in kwargs.items() if", "[] for t in namespace.target_regions: parts = t.split('=', 1) if", "namespace.boot_diagnostics_storage: namespace.boot_diagnostics_storage = get_storage_blob_uri(cmd.cli_ctx, namespace.boot_diagnostics_storage) # endregion # region VMSS", "required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name', 'load_balancer',", "keyvault_usage validate_keyvault(cmd, namespace) else: if kv and not is_valid_resource_id(kv): raise", "'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s',", "image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get(", "int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len", "'loadBalancer': # LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix',", "'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type',", "new storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage account", "1: ids = [r.id for r in role_defs] err =", "logger.debug(\"W/o STD LB, defaulting to '%s' under because single placement", "not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile =", "\"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"]", "'{}'\" raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def", "else: # STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise", "'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx,", "nothing specified, try to find an existing vnet and subnet", "CloudError as ex: logger.warning(\"Querying the image of '%s' failed for", "prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password:", "else: err = \"'Standard' load balancer is required because 'single", "= 0 for i in range(24, 16, -1): if _subnet_capacity_check(i,", "elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard' load", "in arg {3}' if 'certificateUrl' not in cert: errors.append(message.format('certificateUrl', idx,", "if username.lower() in disallowed_user_names: raise CLIError(\"This user name '{}' meets", "if getattr(namespace, 'public_ip_sku', None): from azure.cli.core.profiles import ResourceType PublicIPAddressSkuName, IPAllocationMethod", "x in image_version_infos if not x.publishing_profile.exclude_from_latest] if not image_version_infos: raise", "return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace):", "'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested', 'Standard_DS15_v2', 'Standard_DS15_v2_Promo', 'Standard_DS15_v2_Nested', 'Standard_D40_v3', 'Standard_D40s_v3',", "logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id,", "('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer',", "_validate_vm_create_nics(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if", "'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd,", "if 'Premium' in namespace.storage_sku else 'Standard' account = next( (a", "== vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group,", "kwargs.items() if not v} return resource_id(**kwargs) if not missing_kwargs else", "== StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name',", "has no such needs so far if getattr(namespace, 'public_ip_sku', None):", "not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1: raise CLIError(\"Multiple possible values", "validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks',", "= ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not", "disallowed_user_names: raise CLIError(\"This user name '{}' meets the general requirements,", "cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2'", "namespace.os_type: namespace.os_type = 'windows' if 'windows' in namespace.os_offer.lower() else 'linux'", "raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') # endregion #", "'%s'\", namespace.storage_profile) if for_scale_set: # VMSS lacks some parameters, so", "else: # did not specify image XOR attach-os-disk raise CLIError('incorrect", "OS if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: #", "storage account in target resource group that matches the VM's", "of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i)", "cannot contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or", "MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role' is only", "namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except", "\"permanent storage, back up your keys to a safe location.\",", "have the 3 of the following: 1 lower case character,", "of OS (linux or windows) :return: errors if any were", "x in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible", "source) source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd,", "windows)\" }] }] :param dict secrets: Dict fitting the JSON", "not [x for x in (temp.location_info or []) if x.zones]:", "a new storage account namespace.storage_account_type = 'new' logger.debug('no suitable storage", "ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage", "def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion", "rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute',", "or []) elif res['type'].lower() == 'galleries': image_info = compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'],", "vaultCertificates array at secret ' \\ 'index {1} and vaultCertificate", "= 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type ==", "in names_or_ids: if not is_valid_resource_id(val): val = resource_id( subscription=subscription_id, resource_group=resource_group,", "namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not found. It will", "azure.cli.core.profiles import ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None", "if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value", "viable storage account in target resource group namespace.storage_account = account.name", "for x in identities if x != MSI_LOCAL_ID] if user_assigned_identities", "the target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET", "off for zonal scale-sets or with\" \" 100+ instances\") def", "managed OS disk from custom image' elif profile == StorageProfile.ManagedPirImage:", "try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg,", "import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME", "only applicable on Windows VM scaleset') if not namespace.public_ip_per_vm and", "namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not", "or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd, namespace) else: if kv and", "'image_id' except CloudError: err = 'Invalid image \"{}\". Use a", "if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx,", "'--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name,", "private_key_filepath = public_key_filepath[:-4] else: private_key_filepath = public_key_filepath + '.private' content", "'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in", "NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ',", "\"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise", "+ 1): raise CLIError('The password length must be between {}", "= (os_type.lower() == 'linux') max_length = 72 if is_linux else", "_get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx)", "= 'new' logger.debug(\"application gateway '%s' not found. It will be", "temp = next((x for x in sku_infos if x.name.lower() ==", "namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris", "| --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise CLIError('usage error:", "and 1 special character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or", "idx, secret in enumerate(narg_secret): if 'sourceVault' not in secret: errors.append(", "else: from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client storage_client", "StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd,", "d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if", "from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup =", "'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3',", "the 3 of the following: 1 lower case character, 1", "names_or_ids = getattr(namespace, 'application_security_groups') ids = [] if names_or_ids ==", "(most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched", "logger.debug('new application gateway will be created') # AppGateway frontend required", "vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int", "= \"'Standard' load balancer is required for zonal scale-sets\" elif", "azure.cli.core.commands.client_factory import get_subscription_id nics_value = namespace.nics nics = [] if", "def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud", "next((x for x in images if x['urnAlias'].lower() == namespace.image.lower()), None)", "._vm_utils import MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i]", "get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils", "def validate_vmss_disk(cmd, namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name,", "source_disk = info.id return (source_blob_uri, source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace):", "= matched['version'] return 'urn' # 5 - check if an", "'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3', 'Standard_D4_v2_ABC', 'Standard_D13_v2_ABC', 'Standard_F8_ABC', 'Standard_F16s_v2', 'Standard_D5_v2', 'Standard_D14_v2', 'Standard_D5_v2_Promo',", "Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify password in", "forbidden.remove(prop) # set default storage SKU if not provided and", "balancer (if any) being used balancer_type = 'None' if namespace.load_balancer", "pick an id from '{}'\" raise CLIError(err.format(role, ids)) role_id =", "= 'new' logger.debug('no suitable subnet found. One will be created.')", "if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err) if not is_linux", "for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import", "errors.append(message.format('certificateStore', idx, jdx, idx_arg)) if errors: raise CLIError('\\n'.join(errors)) # region", "endregion # region VMSS Create Validators def _get_default_address_pool(cli_ctx, resource_group, balancer_name,", "t in namespace.target_regions: parts = t.split('=', 1) if len(parts) ==", "'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3',", "not nics_value: namespace.nic_type = 'new' logger.debug('new NIC will be created')", "max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit", "validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence,", "character') def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub'))", "namespace.resource_group_name subscription_id = get_subscription_id(cmd.cli_ctx) names_or_ids = getattr(namespace, 'application_security_groups') ids =", "else: raise CLIError('Unrecognized image type: {}'.format(image_type)) else: # did not", "password cannot be used with SSH authentication type') validate_ssh_key(namespace) if", "balancer_type = 'loadBalancer' elif namespace.application_gateway: balancer_type = 'applicationGateway' if balancer_type", "subnet '%s' found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id =", "check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does", "no such needs so far if getattr(namespace, 'public_ip_sku', None): from", "namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd, namespace): if namespace.load_balancer_type is", "_validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd,", "if id_comps['name'] == vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx,", "namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found. It will", "namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots = [] if", "= cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for t in", "'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG '%s'\", namespace.nsg) else:", "namespace.public_ip_address: raise CLIError('--public-ip-address can only be used when creating a", "def _get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client =", "existing application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new'", "= _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd,", "MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID:", "namespace.attach_data_disks] if not namespace.os_type: namespace.os_type = 'windows' if 'windows' in", "--instance-id ID') def process_disk_or_snapshot_create_namespace(cmd, namespace): from msrestazure.azure_exceptions import CloudError validate_tags(namespace)", "import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd, namespace) if zone_info: sku_infos", "image_type = _parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE", "# did not specify image XOR attach-os-disk raise CLIError('incorrect usage:", "= is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and", "be created') return if not isinstance(nics_value, list): nics_value = [nics_value]", "namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace) if namespace.storage_profile in", "['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku']", "CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx),", "username): raise CLIError(linux_err if is_linux else win_err) if is_linux and", "namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint:", "_subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for s in", "a uri? source_blob_uri = source elif '/disks/' in source.lower(): source_disk", "role else: try: uuid.UUID(role) role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format( client.config.subscription_id, role) except", "list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in sku_infos if", "content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command or namespace.assign_identity is", "SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info,", "from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value =", "profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk from Azure", "namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids if hasattr(namespace, 'primary_nic')", "= [] if names_or_ids == [\"\"] or not names_or_ids: return", "not namespace.admin_password: namespace.admin_password = prompt_pass('Admin Password: ', confirm=True) except NoTTYException:", "= [] try: loaded_secret = [validate_file_or_dict(secret) for secret in secrets]", "out of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix", "in namespace.os_offer.lower() else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks", "'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3',", "need to be a supported image in the marketplace #", "'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3']", "def _validate_vm_create_nics(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import", "return int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value should", "azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import", "sku_infos if x.name.lower() == size_info.lower()), None) # For Stack (compute", "attempt to match an URN pattern urn_match = re.match('([^:]*):([^:]*):([^:]*):([^:]*)', namespace.image)", "validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import", "zone_info, size_info): from ._vm_utils import list_sku_info if not namespace.location: get_default_location_from_resource_group(cmd,", "= [] namespace.data_snapshots = [] if namespace.data_disk_sources: for data_disk_source in", "rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway)", "return 'attach to existing unmanaged OS disk' elif profile ==", "\"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\",", "logger.debug(\"using specified NSG '%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified", "msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk = None source_snapshot", "return 'uri' # 4 - attempt to match an URN", "logger.debug('no suitable storage account found. One will be created.') def", "'Standard_D15_v2_ABC', 'Standard_M64ms', 'Standard_M64s', 'Standard_M128-64ms', 'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3',", "these out props_to_remove = ['attach_os_disk', 'storage_account'] for prop in props_to_remove:", "str \"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client", "x != MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage", "'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing': required.append('backend_pool_name') forbidden = ['nat_pool_name',", "parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type =", "\\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern, username): raise CLIError(linux_err", "if not username: raise CLIError(\"admin user name can not be", "disallowed for this image. Please try a different value.\".format(username)) return", "azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys from ._client_factory import", "CLIError('usage error: unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif", "if x]) # pylint: disable=line-too-long if count < 3: raise", "', '.join([n.name for n in lb.inbound_nat_pools]))) elif not lb.inbound_nat_pools: #", "character, 1 upper case character, 1 number and 1 special", "import MSI_LOCAL_ID for i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID:", "matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return 'urn' #", "one from {}' raise CLIError(err.format(namespace.image, [x['urnAlias'] for x in images]))", "except CloudError as ex: logger.warning(\"Querying the image of '%s' failed", "the VM/VMSS because availablity zone is not yet \" \"supported.", "an image based OS if not namespace.storage_sku and namespace.storage_profile in", "'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo',", "enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name,", "scope): import re import uuid from azure.cli.core.commands.client_factory import get_mgmt_service_client from", "lb_name): from msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return", "'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3',", "1 - check if a fully-qualified ID (assumes it is", "namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID')", "'with minimum Compute API version of 2017-12-01') if namespace.identity_scope: if", "from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku =", "= parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name'])", "get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if", "access to the VM. If using machines without \" \"permanent", "'%s' and subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 -", "of the following: 1 lower case character, 1 upper case", "so use 'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb,", "def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group from vault name", "'storage_account', 'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile ==", "ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK) resource_group", "rg, lb_name, 'load_balancers') if not namespace.nat_pool_name: if len(lb.inbound_nat_pools) > 1:", "source_disk = None source_snapshot = None if urlparse(source).scheme: # a", "namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in", "of the key vault :return: resource group name or None", "return val kwargs = { 'name': val, 'resource_group': resource_group, 'namespace':", "= None logger.debug('no public IP address will be used') elif", "if namespace.vm_sku is None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name", "for x in images if x['urnAlias'].lower() == namespace.image.lower()), None) if", "x in allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values:", "create --accelerated-networking --size Standard_DS1_v2' and # get it from the", "enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault' not in", "compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint:", "_validate_vm_create_availability_set(cmd, namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import", "'%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load", "raise CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME", "is only applicable on Windows VM scaleset') if not namespace.public_ip_per_vm", "namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except CloudError: err = 'Invalid", "for VM. VMSS has no such needs so far if", "= compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine", "if not temp or not [x for x in (temp.location_info", "= ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2',", "CLIError('Usage error: --vm-domain-name can only be used when --public-ip-per-vm is", "res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image(", "namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no NSG", "namespace.authentication_type: # apply default auth type (password for Windows, ssh", "def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku", "forbidden, description='network balancer: load balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group',", "image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized", "= matched['publisher'] namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version =", "key files '%s' and '%s' have been generated under ~/.ssh", "only applicable when assign system identity\") # keep 'identity_role' for", "with backports kernel # Oracle Linux 7.4, Windows Server 2016,", "gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error:", "parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) #", "image_version_infos = [x for x in image_version_infos if not x.publishing_profile.exclude_from_latest]", "an image ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 -", "machines without \" \"permanent storage, back up your keys to", "# STORAGE PROFILE #1 namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE", "a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found.", "PRIORITY [--eviction-policy POLICY]') # endregion # region disk, snapshot, image", "account.name) else: # 4 - nothing specified - create a", "if from_set_command or namespace.assign_identity is not None: identities = namespace.assign_identity", "group' is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from", "re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password) contains_special_char = re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+',", "image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if res['type'].lower()", "'Standard_M128s', 'Standard_M128ms', 'Standard_L8s_v2', 'Standard_L16s_v2', 'Standard_L32s_v2', 'Standard_L64s_v2', 'Standard_L96s_v2', 'SQLGL', 'SQLGLCore', 'Standard_D4_v3',", "} missing_kwargs = {k: v for k, v in kwargs.items()", "candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len", "and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type):", "with open(string_or_file, 'r') as f: content = f.read() elif not", "[] if names_or_ids == [\"\"] or not names_or_ids: return for", "id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if not role_defs:", "raise CLIError('The password length must be between {} and {}'.format(min_length,", "None: from azure.cli.core.cloud import AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku", "did not specify image XOR attach-os-disk raise CLIError('incorrect usage: --image", "('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos',", "namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute') return 'image_id' except", "CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory", "'Standard_DS5_v2', 'Standard_DS14_v2', 'Standard_DS5_v2_Promo', 'Standard_DS14_v2_Promo', 'Standard_F16', 'Standard_F16s', 'Standard_M64-32ms', 'Standard_M128-32ms', 'Standard_D32_v3', 'Standard_D32s_v3',", "you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False): if from_set_command", "specify a capable one. 'az vm list-skus' can be \"", "narg_secret in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault'", "aval_sizes: return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2',", "is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username): raise CLIError(linux_err)", "logger.debug(\"use Standard sku as single placement group is turned off\")", "32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask =", "!= 'windows': raise CLIError('usage error: --license-type is only applicable on", "= ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile", "scaleset will be missing ssh/rdp, so warn here. logger.warning(\"No inbound", "balancer will be created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group", "[StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint: disable=line-too-long namespace.storage_sku = 'Standard_LRS' if for_scale_set", "public IP '%s' not found. It will be created.\", namespace.public_ip_address)", "error: [--keyvault NAME --resource-group NAME | --keyvault ID]') kv =", "profile ' 'with minimum Compute API version of 2017-12-01') if", "namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows':", "\"used to find such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def", "in distros: if p.lower() == publisher and (o is None", "[StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace)", "namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d, namespace.resource_group_name, 'disks', 'Microsoft.Compute') for d", "StorageProfile.SASpecializedOSDisk else: # STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif", "_validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace)", "from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType client =", "ex.message) # pylint: disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage:", "in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location can't", "_validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve OS", "'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info", "namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot) if not namespace.os_type: raise CLIError(\"usage error:", "source): from msrestazure.azure_exceptions import CloudError source_blob_uri = None source_disk =", "raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names", "namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if namespace.identities: from", "= 'Secret is missing {0} within vaultCertificates array at secret", "'create unmanaged OS disk from Azure Marketplace image' elif profile", "namespace.location), None) if account: # 3 - nothing specified -", "validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = [] for n", "public IP address will be used') elif namespace.public_ip_address is None:", ":return: errors if any were found :rtype: list \"\"\" is_windows", "found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision): mask", "is None or o.lower() == offer) and (s is None", "Specify '--os-type' argument.\") if not namespace.authentication_type: # apply default auth", "get_subscription_id if namespace.availability_set: as_id = parse_resource_id(namespace.availability_set) name = as_id['name'] rg", "| --keyvault ID]') kv = namespace.keyvault rg = namespace.resource_group_name if", "storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if for_scale_set: #", "if rg: if not kv or is_valid_resource_id(kv): raise keyvault_usage validate_keyvault(cmd,", "creating a new load ' 'balancer or application gateway frontend.')", "not is_linux and username.endswith('.'): raise CLIError(win_err) disallowed_user_names = [ \"administrator\",", "\" \"supported. Please use '--location' to specify a capable one.", "disable=import-error from knack.log import get_logger from knack.util import CLIError from", "profile # start with the required/forbidden parameters for VM if", "# pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name for n in lb.inbound_nat_pools])))", "if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities',", "error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2',", "== n } }) namespace.nics = nics namespace.nic_type = 'existing'", "namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be", "not v} return resource_id(**kwargs) if not missing_kwargs else None def", "disk created from generalized VHD' elif profile == StorageProfile.SAPirImage: return", "\"supported. Please use '--location' to specify a capable one. 'az", "PublicIPAddressSkuName, IPAllocationMethod = cmd.get_models('PublicIPAddressSkuName', 'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value:", "balancer') if namespace.load_balancer: rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name']", "s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() ==", "namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network')", "' 'You can use --generate-ssh-keys to let CLI generate one", "namespace.storage_sku else 'Standard' account = next( (a for a in", "for p, o, s in distros: if p.lower() == publisher", "Value. ' 'You can use --generate-ssh-keys to let CLI generate", "== '': namespace.load_balancer_type = None logger.debug('no load balancer will be", "get_mgmt_service_client return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from", "'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower() not in [x.lower()", "'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are not exposed", "user assigned identity is only available under profile ' 'with", "doesn't exist.\".format(role)) elif len(role_defs) > 1: ids = [r.id for", "and using an image based OS if not namespace.storage_sku and", "CLIError(\"incorrect '--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name", "# AppGateway frontend required = [] if namespace.app_gateway_type == 'new':", "2 - params for new storage account specified namespace.storage_account_type =", "_validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd,", "err: raise CLIError('Error decoding secrets: {0}'.format(err)) for idx_arg, narg_secret in", "in enumerate(loaded_secret): for idx, secret in enumerate(narg_secret): if 'sourceVault' not", "load balancer will be used') elif namespace.load_balancer is None: namespace.load_balancer_type", "storage profile # start with the required/forbidden parameters for VM", "data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace):", "password length must be between {} and {}'.format(min_length, max_length)) contains_lower", "else: for jdx, cert in enumerate(secret['vaultCertificates']): message = 'Secret is", "OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS']", "not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can only", "balancer is required for zonal scale-sets\" elif namespace.instance_count > 100:", "target resource group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in", "informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: #", "re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password) contains_digit = re.findall('[0-9]+', password)", "else 'applicationGateway' logger.debug(\"W/o STD LB, defaulting to '%s' under because", "\"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store", "'*1.5' so we have enough leeway for over-provision factor =", "subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if", "source_snapshot = None if urlparse(source).scheme: # a uri? source_blob_uri =", "== size_info.lower()), None) # For Stack (compute - 2017-03-30), Resource_sku", "aval_sizes] if size not in aval_sizes: return new_4core_sizes = ['Standard_D3_v2',", "source.lower(): source_disk = source elif '/snapshots/' in source.lower(): source_snapshot =", "namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if", "role, re.I): role_id = role else: try: uuid.UUID(role) role_id =", "= compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in sizes if", "namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing storage account", "and subnet...') # if nothing specified, try to find an", "if namespace.authentication_type == 'password': if namespace.ssh_key_value or namespace.ssh_dest_key_path: raise ValueError(", "'--role {}' is not applicable as the '--scope' is not", "'Standard_DS4_v2_Promo', 'Standard_DS13_v2_Promo', 'Standard_DS14-8_v2_Promo', 'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3',", "not None: identities = namespace.assign_identity or [] from ._vm_utils import", "'IPAllocationMethod', resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation", "vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) +", "== StorageProfile.ManagedCustomImage: # extract additional information from a managed custom", "= 'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name']) else:", "' \\ 'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx,", "image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version)", "namespace.location) temp = next((x for x in sku_infos if x.name.lower()", "NSG will be created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg", "(password for Windows, ssh for Linux) by examining the OS", "'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC', 'Standard_F32s_v2', 'Standard_D15_v2', 'Standard_D15_v2_Promo', 'Standard_D15_v2_Nested',", "if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg)", "namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd, namespace): from msrestazure.tools import", "'storage_account'] for prop in props_to_remove: if prop in required: required.remove(prop)", "_validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name", "for x in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s", "will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]:", "application gateway '%s'\", namespace.application_gateway) except CloudError: namespace.app_gateway_type = 'new' logger.debug(\"application", "contains_digit, contains_special_char] if x]) # pylint: disable=line-too-long if count <", "name can not be empty\") is_linux = (os_type.lower() == 'linux')", "move to its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace):", "CloudError: namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint:", "auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk']", "'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3',", "error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role, scope):", "= source else: compute_client = _compute_client_factory(cli_ctx) # pylint: disable=no-member try:", "load balancer is required because 'single placement group' is turned", "'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos',", "_validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import parse_resource_id", "'-backports'), ('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')]", "in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision): break", "if count < 3: raise CLIError('Password must have the 3", "of balancer (if any) being used balancer_type = 'None' if", "or \\ _get_default_address_pool(cmd.cli_ctx, rg, ag_name, 'application_gateways') logger.debug(\"using specified existing application", "if balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try:", "is required for zonal scale-sets\" elif namespace.instance_count > 100: err", "in secret['sourceVault']: errors.append( 'Secret is missing sourceVault.id key at index", "vaultCertificates array or it is empty at index {0} in", "'^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle', 'oracle-linux', '^7.4'),", "sourceVault key at index {0} in arg {1}'.format( idx, idx_arg))", "count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0], regional_replica_count=replica_count)) namespace.target_regions = regions_info", "'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3',", "idx, idx_arg)) if 'vaultCertificates' not in secret or not secret['vaultCertificates']:", "check if a fully-qualified ID (assumes it is an image", "zone is not yet \" \"supported. Please use '--location' to", "x in identities if x != MSI_LOCAL_ID] if user_assigned_identities and", "extract vnet information needed to verify the defaults we are", "= '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not client:", "None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones", "re.findall(r'[ `~!@#$%^&*()=+_\\[\\]{}\\|;:.\\/\\'\\\",<>?]+', password) count = len([x for x in [contains_lower,", "namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones,", "if namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is None:", "Standard sku as single placement group is turned off\") elif", "= parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg,", "namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error:", "x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num", "'^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'),", "if namespace.vnet_type == 'new': if namespace.subnet_address_prefix is None: cidr =", "= _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = []", "existing storage account '%s'\", storage_id['name']) else: # 2 - params", "_get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace,", "missing_kwargs else None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val,", "possible values found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint:", "'Standard_D64_v3', 'Standard_D64s_v3', 'Standard_E64_v3', 'Standard_E64s_v3', 'Standard_E64-16s_v3', 'Standard_E64-32s_v3', 'Standard_F64s_v2', 'Standard_F72s_v2', 'Standard_M128s', 'Standard_M128ms',", "elif len(role_defs) > 1: ids = [r.id for r in", "else 1 return ((1 << (32 - mask)) - 2)", "# Oracle Linux 7.4, Windows Server 2016, Windows Server 2012R2", "the VM. If using machines without \" \"permanent storage, back", "--license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace) if", "found for '{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name',", "(32 - mask)) - 2) > int(vmss_instance_count * factor) def", "import CloudError source_blob_uri = None source_disk = None source_snapshot =", "StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile", "'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic', 'centos', '^7.4'), ('coreos', 'coreos',", "balancer '%s' not found. It will be created.\", namespace.load_balancer) elif", "== PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation = IPAllocationMethod.static.value def _validate_vmss_create_public_ip(cmd,", "= 'None' if namespace.load_balancer is None and namespace.application_gateway is None:", "validate_tags) from azure.cli.core.util import hash_string from azure.cli.command_modules.vm._vm_utils import check_existence, get_target_network_api,", "balancer is required because 'single placement group' is turned off\"", "if any were found :rtype: list \"\"\" is_windows = os_type", "Windows, ssh for Linux) by examining the OS type namespace.authentication_type", "unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed", "needed to verify the defaults we are coming out vnet_ip_address,", "namespace='Microsoft.Network', type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd,", "_validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise", "ResourceType.MGMT_KEYVAULT).vaults for vault in client.list(): id_comps = parse_resource_id(vault.id) if id_comps['name']", "'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now", "the JSON description above :param string os_type: the type of", "= namespace.keyvault rg = namespace.resource_group_name if rg: if not kv", "find storage account in target resource group that matches the", "an existing vnet and subnet in the target resource group", "NIC(s) will be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk,", "raise CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' \"", "namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace)", "and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower() ==", "import urlparse # pylint: disable=import-error from knack.log import get_logger from", "return resource_id(**kwargs) if not missing_kwargs else None def _get_nic_id(cli_ctx, val,", "os_type: the type of OS (linux or windows) :return: errors", "None) # For Stack (compute - 2017-03-30), Resource_sku doesn't implement", "= ['attach_os_disk', 'storage_account'] for prop in props_to_remove: if prop in", "- user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified", "so we have enough leeway for over-provision factor = 1.5", "not check_existence(cmd.cli_ctx, name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}'", "\\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault =", "{0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret in", "subnet_bit_mask_len)) > vnet_int: # overflows? candidate_int = candidate_int - 2", "CLIError('Please specify password in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password,", "special characters \\/\"[]:|<>+=;,?*@#()! or start with $ or -' win_err", "v in kwargs.items() if not v} return resource_id(**kwargs) if not", "applicable as the '--scope' is not provided\".format( namespace.identity_role)) user_assigned_identities =", "_get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a, b, c, d", "return '{0}.{1}.{2}.{3}/{4}'.format(int(candaidate_str[0:8], 2), int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask)", "lb: namespace.load_balancer_type = 'existing' namespace.backend_pool_name = namespace.backend_pool_name or \\ _get_default_address_pool(cmd.cli_ctx,", "Configuring plan settings \" \"will be skipped\", namespace.image, ex.message) #", "the MIT License. See License.txt in the project root for", "arg {1}'.format( idx, idx_arg)) if 'vaultCertificates' not in secret or", "used\", account.name) else: # 4 - nothing specified - create", "(os_type.lower() == 'linux') max_length = 72 if is_linux else 123", "import CloudError try: compute_client = _compute_client_factory(cmd.cli_ctx) if namespace.os_version.lower() == 'latest':", "[('canonical', 'UbuntuServer', '^16.04'), ('suse', 'sles', '^12-sp3'), ('redhat', 'rhel', '^7.4'), ('openlogic',", "usage: --load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the", "any were found :rtype: list \"\"\" is_windows = os_type ==", "namespace.nsg_type = None logger.debug('no NSG will be used') elif namespace.nsg", "and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error) def process_image_create_namespace(cmd,", "x.name.lower() == size_info.lower()), None) # For Stack (compute - 2017-03-30),", "(o is None or o.lower() == offer) and (s is", "return 'create managed OS disk from custom image' elif profile", "\"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"guest\", \"owner\", \"root\", \"server\", \"sql\",", "getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage error: '--role {}'", "_validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage", "else: namespace.public_ip_address_type = 'new' logger.debug(\"specified public IP '%s' not found.", "not be empty\") is_linux = (os_type.lower() == 'linux') # pylint:", "is disabled\", balancer_type) elif namespace.load_balancer: balancer_type = 'loadBalancer' elif namespace.application_gateway:", "AppGateway frontend required = [] if namespace.app_gateway_type == 'new': required.append('app_gateway_sku')", "len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized image informations", "namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd,", "AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace,", "namespace.zones or namespace.instance_count > 100: if namespace.single_placement_group is None: namespace.single_placement_group", "Updates the namespace and returns the type for subsequent processing.", "image validators def validate_vm_disk(cmd, namespace): namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name,", "for x in new_4core_sizes] if size not in new_4core_sizes: compute_client", "matching subnet for vnet_match in (v for v in client.list(rg)", "was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using", "namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace) _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True)", "CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def _resolve_role_id(cli_ctx, role,", "is None: raise CLIError('usage error: --platform-fault-domain-count COUNT --zones ZONES') if", "'Standard_D32_v3', 'Standard_D32s_v3', 'Standard_D64-32s_v3', 'Standard_E32_v3', 'Standard_E32s_v3', 'Standard_E32-8s_v3', 'Standard_E32-16_v3', 'Standard_D5_v2_ABC', 'Standard_D14_v2_ABC', 'Standard_F16_ABC',", "created') # Public-IP SKU is only exposed for VM. VMSS", "'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk:", "if x.zones]: raise CLIError(\"{}'s location can't be used to create", "storage_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_STORAGE).storage_accounts # find storage account in target", "def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name nic_ids = [] for", "for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is", "def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower() == 'linux')", "found and will be created\", storage_id['name']) else: from azure.cli.core.profiles import", "bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb", "and sku.lower() not in [x.lower() for x in allowed_skus]: raise", "logger.debug('no subnet specified. Attempting to find an existing Vnet and", "(not subnet_is_id and not vnet): raise CLIError(\"incorrect '--subnet' usage: --subnet", "'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x in", "None logger.debug('no NSG will be used') elif namespace.nsg is None:", "keys), and 'base_name.pub'(with public keys) public_key_filepath = string_or_file if public_key_filepath[-4:].lower()", "'Premium' if 'Premium' in namespace.storage_sku else 'Standard' account = next(", "found. It will be created.\", namespace.application_gateway) elif namespace.application_gateway == '':", "rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array", "'%s' failed for an error '%s'. Configuring plan settings \"", "isinstance(nics_value, list): nics_value = [nics_value] for n in nics_value: nics.append({", "'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return", "sku_infos = list_sku_info(cmd.cli_ctx, namespace.location) temp = next((x for x in", "to be a supported image in the marketplace # Ubuntu", "def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet =", "['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile ==", "--load-balancer NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the type", "'new' logger.debug('new load balancer will be created') if namespace.load_balancer_type ==", "'Microsoft.KeyVault') def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace):", "kwargs = { 'name': val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type':", "managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS',", "factor = 1.5 if over_provision else 1 return ((1 <<", "int(candaidate_str[8:16], 2), int(candaidate_str[16:24], 2), int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace):", "and not getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if", "of range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix =", "'windows' or namespace.admin_password) else 'ssh' if namespace.os_type.lower() == 'windows' and", "- int(mask) if vnet_bit_mask_len <= subnet_bit_mask_len: raise CLIError(error_msg) candidate_int =", "'ssh' if namespace.os_type.lower() == 'windows' and namespace.authentication_type == 'ssh': raise", "not exist.\".format(name)) namespace.availability_set = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name)", "identities and MSI_LOCAL_ID not in identities: raise CLIError(\"usage error: '--scope'/'--role'", "logger.debug('no application gateway will be used') elif namespace.application_gateway is None:", "msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set:", "= string_or_file if os.path.exists(string_or_file): logger.info('Use existing SSH public key file:", "cert in enumerate(secret['vaultCertificates']): message = 'Secret is missing {0} within", "SP3, RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with", "is missing sourceVault.id key at index {0} in arg {1}'.format(", "if not image_version_infos: raise CLIError('There is no latest image version", "= namespace.location nics = getattr(namespace, 'nics', None) if not vnet", "for vnet_match in (v for v in client.list(rg) if v.location", "namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s' and subnet '%s'\",", "'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x", "NSG '%s' not found. It will be created.\", namespace.nsg) elif", "re if not username: raise CLIError(\"admin user name can not", "balancer will be used') elif namespace.load_balancer is None: namespace.load_balancer_type =", "namespace): \"\"\" Systematically determines what type is supplied for the", "%s', string_or_file) with open(string_or_file, 'r') as f: content = f.read()", "parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name)", "a.sku.tier.value == sku_tier and a.location == namespace.location), None) if account:", "namespace.os_publisher = urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version", "= vnet_cidr.split('/') vnet_bit_mask_len = 32 - int(mask) vnet_int = _convert_to_int(vnet_ip_address,", "RHEL 7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports", "= resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=rg, namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified", "information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse", "validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info", "validate_nsg_name(cmd, namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "}, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name (only", "'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3',", "new_4core_sizes] if size not in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes", "for Linux) by examining the OS type namespace.authentication_type = 'password'", "== StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID namespace.attach_os_disk =", "i = 0 for i in range(24, 16, -1): if", "and (s is None or re.match(s, sku, re.I)): namespace.accelerated_networking =", "to SSH Key Value. ' 'You can use --generate-ssh-keys to", "import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK)", "if _check_subnet(s)), None) if not result: continue namespace.subnet = result.name", "option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx), balancer_type, None) if not", "to a safe location.\", private_key_filepath, public_key_filepath) else: raise CLIError('An RSA", "be empty\") is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long", "'az vm create --accelerated-networking --size Standard_DS1_v2' and # get it", "azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set, validate_tags) from azure.cli.core.util import", "is None: namespace.ultra_ssd_enabled = True # Now verify that the", "that matches the VM's location with a matching subnet for", "}) namespace.nics = nics namespace.nic_type = 'existing' namespace.public_ip_address_type = None", "'arg {1} ' errors.append(err.format(idx, idx_arg)) else: for jdx, cert in", "- existing storage account specified namespace.storage_account_type = 'existing' logger.debug(\"using specified", "source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if", "_validate_vm_vmss_msi(cmd, namespace) if namespace.license_type and namespace.os_type.lower() != 'windows': raise CLIError('usage", "namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing' namespace.backend_pool_name", "use in VM Creation Secrets JSON structure [{ \"sourceVault\": {", "we have enough leeway for over-provision factor = 1.5 if", "account '%s' not found and will be created\", storage_id['name']) else:", "source_blob_uri = None source_disk = None source_snapshot = None if", "in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple possible values", ":param string os_type: the type of OS (linux or windows)", "suitable existing vnet/subnet result = None if not for_scale_set: result", "'Standard_E4_v3', 'Standard_E4s_v3', 'Standard_F2', 'Standard_F2s', 'Standard_F4s_v2', 'Standard_D11_v2', 'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes =", "return new_4core_sizes = ['Standard_D3_v2', 'Standard_D3_v2_Promo', 'Standard_D3_v2_ABC', 'Standard_DS3_v2', 'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo',", "'Standard_DS3_v2_Promo', 'Standard_D12_v2', 'Standard_D12_v2_Promo', 'Standard_D12_v2_ABC', 'Standard_DS12_v2', 'Standard_DS12_v2_Promo', 'Standard_F8s_v2', 'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s',", "# Licensed under the MIT License. See License.txt in the", "_validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd, namespace) _validate_vm_vmss_create_public_ip(cmd, namespace) _validate_vm_create_nics(cmd, namespace)", "namespace.zones: err = \"'Standard' load balancer is required for zonal", "as ex: logger.warning(\"Querying the image of '%s' failed for an", "ValueError: raise CLIError(\"usage error: {}'s replica count must be an", "disk from custom image' elif profile == StorageProfile.ManagedPirImage: return 'create", "PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if not namespace.admin_password:", "contain special characters \\/\"[]:|<>+=;,?*@# or ends with .' if re.findall(pattern,", "s.name.lower() == size), None) if size_info is None or size_info.number_of_cores", "== 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux", "NAME_OR_ID | ' '--application-gateway NAME_OR_ID') # Resolve the type of", "import CloudError validate_tags(namespace) try: # try capturing from VM, a", "images])) def _get_image_plan_info_if_exists(cmd, namespace): from msrestazure.azure_exceptions import CloudError try: compute_client", "errors.append( 'Secret is missing sourceVault key at index {0} in", "vault_name: return id_comps['resource_group'] return None def _get_resource_id(cli_ctx, val, resource_group, resource_type,", "- params for new storage account specified namespace.storage_account_type = 'new'", "def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info =", "balancer = client.get(resource_group, balancer_name) values = [x.name for x in", "rg = parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx,", "azure.cli.command_modules.vm._actions import load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for", "identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity')", "when assign system identity\") # keep 'identity_role' for output as", "= role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace,", "['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image',", "namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise", "msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01',", "'balancer or application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace)", "VHD' elif profile == StorageProfile.SAPirImage: return 'create unmanaged OS disk", "in non-interactive mode.') # validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type", "not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise CLIError(usage_error)", "elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot", "return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision)", "namespace): rg = namespace.resource_group_name nic_ids = [] for n in", "== 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError:", "the --image parameter. Updates the namespace and returns the type", "res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif", "\"test3\", \"user4\", \"user5\"] if username.lower() in disallowed_user_names: raise CLIError(\"This user", "try: compute_client.images.get(namespace.resource_group_name, namespace.image) namespace.image = _get_resource_id(cmd.cli_ctx, namespace.image, namespace.resource_group_name, 'images', 'Microsoft.Compute')", "namespace): namespace.keyvault = _get_resource_id(cmd.cli_ctx, namespace.keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') def process_vm_secret_format(cmd,", "OS disk' elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS", "pylint: disable=line-too-long if count < 3: raise CLIError('Password must have", "under profile ' 'with minimum Compute API version of 2017-12-01')", "'create managed OS disk from Azure Marketplace image' elif profile", "def process_image_create_namespace(cmd, namespace): from msrestazure.tools import parse_resource_id from msrestazure.azure_exceptions import", "len(values) > 1: raise CLIError(\"Multiple possible values found for '{0}':", "raise CLIError(\"Availability set '{}' does not exist.\".format(name)) namespace.availability_set = resource_id(", "validate_tags(namespace) if namespace.source: usage_error = 'usage error: --source {SNAPSHOT |", "with $ or -' win_err = r'admin user name cannot", "is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name", "range of 2^16 subnet size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr,", "SUBNET_NAME --vnet-name VNET_NAME\") subnet_exists = \\ check_existence(cmd.cli_ctx, subnet, rg, 'Microsoft.Network',", "(os_type.lower() == 'linux') # pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if", "if image_type == 'uri': # STORAGE PROFILE #2 namespace.storage_profile =", "_validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size = getattr(namespace, 'size',", "under ~/.ssh to \" \"allow SSH access to the VM.", "for_scale_set=True) _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace)", "elif profile == StorageProfile.ManagedPirImage: return 'create managed OS disk from", "namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not found.", "exposed yet for VMSS, so use 'getattr' to avoid crash", "from the error aval_sizes = ['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2',", "msrestazure.tools import is_valid_resource_id from msrestazure.azure_exceptions import CloudError import re #", "import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id if namespace.availability_set: as_id", "factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking is None: size =", "application gateway frontend.') namespace.public_ip_address = '' _validate_vm_vmss_create_public_ip(cmd, namespace) def _validate_vm_create_nics(cmd,", "source_disk, source_snapshot) def process_disk_encryption_namespace(cmd, namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name,", "urn_match.group(3) namespace.os_version = urn_match.group(4) if not any([namespace.plan_name, namespace.plan_product, namespace.plan_publisher]): image_plan", "else: # 2 - params for new storage account specified", "should be a subrange of --vnet-address-prefix's\" # extract vnet information", "azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs = {", "disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources: raise", "next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier", "| ' '--application-gateway NAME_OR_ID') # Resolve the type of balancer", "return 'create unmanaged OS disk created from generalized VHD' elif", "_check_subnet(s)), None) if not result: continue namespace.subnet = result.name namespace.vnet_name", "False and std_lb_is_available: LBSkuName = cmd.get_models('LoadBalancerSkuName', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is", "namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len): a,", "for the specific storage profile # start with the required/forbidden", "(c) Microsoft Corporation. All rights reserved. # Licensed under the", "\"\"\" is_windows = os_type == 'windows' errors = [] try:", "resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id", "find an existing vnet and subnet in the target resource", "= [x.lower() for x in new_4core_sizes] if size not in", "= get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group that", "the following: 1 lower case character, 1 upper case character,", "not provided\".format( namespace.identity_role)) user_assigned_identities = [x for x in identities", "is not None and namespace.zones is None: raise CLIError('usage error:", "any) being used balancer_type = 'None' if namespace.load_balancer is None", "MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') if not", "with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import", "if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name", "'networkInterfaces', 'Microsoft.Network') def validate_vm_nic(cmd, namespace): namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name)", "required.append('app_gateway_capacity') if namespace.vnet_type != 'new': required.append('app_gateway_subnet_address_prefix') elif namespace.app_gateway_type == 'existing':", "list \"\"\" is_windows = os_type == 'windows' errors = []", "scenario res_id = _get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res =", "# For Stack (compute - 2017-03-30), Resource_sku doesn't implement location_info", "parameter validation for the specific storage profile # start with", "gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest', '']: image_version_infos", "\"guest\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\",", "namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd,", "namespace, for_scale_set=True) _validate_vmss_single_placement_group(namespace) _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace) _validate_vmss_create_subnet(namespace) _validate_vmss_create_public_ip(cmd, namespace) _validate_vmss_create_nsg(cmd, namespace)", "'ssh': raise CLIError('SSH not supported for Windows VMs.') # validate", "'Microsoft.Storage', 'storageAccounts'): # 1 - existing storage account specified namespace.storage_account_type", "'new' logger.debug(\"specified NSG '%s' not found. It will be created.\",", "VNET in target resource group that matches the VM's location", "msrestazure.azure_exceptions import CloudError validate_tags(namespace) if namespace.source: usage_error = 'usage error:", "pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import", "name, rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not", "= _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member", "'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks =", "is required for scale-sets with 100+ instances\" else: err =", "'Premium' in namespace.storage_sku else 'Standard' account = next( (a for", "def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace): from msrestazure.azure_exceptions import CloudError from msrestazure.tools import", "x.publishing_profile.exclude_from_latest] if not image_version_infos: raise CLIError('There is no latest image", "is not allowed when capturing \" \"images from virtual machines\")", "namespace.vnet_address_prefix, namespace.subnet_address_prefix, 24) def _get_next_subnet_addr_suffix(vnet_cidr, subnet_cidr, new_mask): def _convert_to_int(address, bit_mask_len):", "# 2 - attempt to match an URN pattern urn_match", "location sku_tier = 'Premium' if 'Premium' in namespace.storage_sku else 'Standard'", "raise CLIError(\"{}'s location can't be used to create the VM/VMSS", "usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\") from", "raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile)) logger.debug(\"storage profile '%s'\", namespace.storage_profile) if", "password) count = len([x for x in [contains_lower, contains_upper, contains_digit,", "resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway: raise CLIError('incorrect usage: --load-balancer NAME_OR_ID", "assign system identity\") # keep 'identity_role' for output as logical", "its own command module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace)", "raise CLIError(\"usage error: '--scope'/'--role' is only applicable when assign system", "i in range(len(namespace.identities)): if namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx,", "1 if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: #", "= namespace.resource_group_name nic_ids = [] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx,", "os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd, namespace): from msrestazure.tools import parse_resource_id if", "VM's location with a matching subnet for vnet_match in (v", "logger.debug(\"using existing specified public IP '%s'\", namespace.public_ip_address) else: namespace.public_ip_address_type =", "username): raise CLIError(linux_err) if not is_linux and username.endswith('.'): raise CLIError(win_err)", "if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if", "name '{}'. Please pick an id from '{}'\" raise CLIError(err.format(role,", "PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace,", "if prop in required: required.remove(prop) if prop in forbidden: forbidden.remove(prop)", "from knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict,", "raise CLIError(\"admin user name can not be empty\") is_linux =", "elif profile == StorageProfile.ManagedCustomImage: return 'create managed OS disk from", "be used') def _validate_vm_vmss_create_auth(namespace): if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return", "try: from urllib.parse import urlparse except ImportError: from urlparse import", "val, resource_group, resource_type, resource_namespace): from msrestazure.tools import resource_id, is_valid_resource_id from", "elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type", "availability set '%s'\", namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools", "= (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user", "Create Validators def _parse_image_argument(cmd, namespace): \"\"\" Systematically determines what type", "else: private_key_filepath = public_key_filepath + '.private' content = keys.generate_ssh_keys(private_key_filepath, public_key_filepath)", "the namespace and returns the type for subsequent processing. \"\"\"", "names_or_ids: return for val in names_or_ids: if not is_valid_resource_id(val): val", "profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: #", "= _convert_to_int(vnet_ip_address, vnet_bit_mask_len) subnet_ip_address, mask = subnet_cidr.split('/') subnet_bit_mask_len = 32", "MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO", "['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required = ['os_type', 'attach_os_disk',", "'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import re", "'new' logger.debug(\"specified public IP '%s' not found. It will be", "namespace): if namespace.disk: namespace.disk = _get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute')", "namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri", "subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def", "created.\", namespace.nsg) elif namespace.nsg == '': namespace.nsg_type = None logger.debug('no", "cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error: user assigned identity is only available", "None or size_info.number_of_cores < 8: return # VMs need to", "-------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os try: from urllib.parse import urlparse", "# validate proper arguments supplied based on the authentication type", "StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb']", "res['name']) # pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id", "namespace.os_sku) else: image_version = namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer,", "is None: namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error:", "parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group', namespace.resource_group_name) if check_existence(cmd.cli_ctx, storage_id['name'], rg, 'Microsoft.Storage',", "regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage", "back to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len) return", "contain upper case character A-Z, special characters \\/\"[]:|<>+=;,?*@#()! or start", "= compute_client.gallery_images.get(resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) namespace.os_type = image_info.os_type.value gallery_image_version = res.get('child_name_2',", "namespace): from msrestazure.tools import parse_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id", "'attach_os_disk', None) and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE", "ID namespace.attach_os_disk = _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if", "list, run 'az vm create --accelerated-networking --size Standard_DS1_v2' and #", "coming out vnet_ip_address, mask = vnet_cidr.split('/') vnet_bit_mask_len = 32 -", "namespace, from_set_command=False): if from_set_command or namespace.assign_identity is not None: identities", "namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows': raise", "--accelerated-networking --size Standard_DS1_v2' and # get it from the error", "CloudError from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available", "for i, _ in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i]", "error: --platform-fault-domain-count COUNT --zones ZONES') if namespace.zones or namespace.instance_count >", "from msrestazure.tools import parse_resource_id from azure.cli.core.profiles import ResourceType std_lb_is_available =", "= urn_match.group(1) namespace.os_offer = urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version =", "= parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name,", "msrestazure.azure_exceptions import CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name)", "compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) # pylint: disable=no-member return image.plan", "subnet '%s'\", namespace.vnet_name, namespace.subnet) return # 3 - create a", "'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower() for x", "raise CLIError('Usage error: --vm-domain-name can only be used when --public-ip-per-vm", "elif namespace.instance_count > 100: err = \"'Standard' load balancer is", "values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and namespace.zones", "IMAGE | --attach-os-disk DISK') auth_params = ['<PASSWORD>_password', 'admin_username', 'authentication_type', 'generate_ssh_keys',", "= len(image_version_info.storage_profile.data_disk_images or []) else: raise CLIError('usage error: unrecognized image", "group client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource", "use '--location' to specify a capable one. 'az vm list-skus'", "create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet", "disable=inconsistent-return-statements def _get_storage_profile_description(profile): if profile == StorageProfile.SACustomImage: return 'create unmanaged", "(s is None or re.match(s, sku, re.I)): namespace.accelerated_networking = True", "else 'Standard' account = next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name)", "= image_plan.product namespace.plan_publisher = image_plan.publisher return 'urn' # 3 -", "\\ '/home/{}/.ssh/authorized_keys'.format(namespace.admin_username) def _validate_admin_username(username, os_type): import re if not username:", "$ or -' win_err = r'admin user name cannot contain", "[r.id for r in role_defs] err = \"More than one", "namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key'", "= get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from msrestazure.tools import resource_id, is_valid_resource_id", "import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg = storage_id.get('resource_group',", "raise CLIError(error_msg) # format back to the cidr candaidate_str =", "is missing sourceVault key at index {0} in arg {1}'.format(", "and # get it from the error aval_sizes = ['Standard_D3_v2',", "storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace,", "namespace): namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault:", "VM. If using machines without \" \"permanent storage, back up", "back up your keys to a safe location.\", private_key_filepath, public_key_filepath)", "\" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.key_encryption_keyvault, namespace.resource_group_name, 'vaults',", "allowed_skus]: raise CLIError(\"invalid storage SKU '{}': allowed values: '{}'\".format(sku, allowed_skus))", "if 'sourceVault' in secret and 'id' not in secret['sourceVault']: errors.append(", "\" \"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException", "forbidden, description='network balancer: application gateway') elif balancer_type == 'loadBalancer': #", "namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own", "is only exposed for VM. VMSS has no such needs", "so warn here. logger.warning(\"No inbound nat pool was configured on", "= sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'],", "p, o, s in distros: if p.lower() == publisher and", "= 'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS'", "namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password cannot be", "error: --license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd, namespace)", "[--eviction-policy POLICY]') # endregion # region disk, snapshot, image validators", "capturing \" \"images from virtual machines\") except CloudError: namespace.os_blob_uri, namespace.os_disk,", "match an URN alias (most likely) from azure.cli.command_modules.vm._actions import load_images_from_aliases_doc", "namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id,", "source_blob_uri, source_disk, source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri:", "public_key_filepath) else: raise CLIError('An RSA key file or key value", "one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False):", "azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and", "'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SACustomImage: required = ['image', 'os_type', 'use_unmanaged_disk']", "when --public-ip-per-vm is enabled') if namespace.eviction_policy and not namespace.priority: raise", "StorageProfile.SACustomImage: return 'create unmanaged OS disk created from generalized VHD'", "only exposed for VM. VMSS has no such needs so", "{}'.format(image_type)) else: # did not specify image XOR attach-os-disk raise", "= CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault ID]')", "namespace.nic = _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg =", "int(candaidate_str[24:32], 2), new_mask) def _validate_vm_create_nsg(cmd, namespace): if namespace.nsg: if check_existence(cmd.cli_ctx,", "resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k,", "for i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not", "else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot contain upper", "if not namespace.source_blob_uri and namespace.source_storage_account_id: raise CLIError(usage_error) except CloudError: raise", "namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, namespace.source) if not namespace.source_blob_uri and", "'resource_group', namespace.resource_group_name) ag_name = parse_resource_id(namespace.application_gateway)['name'] client.get(rg, ag_name) namespace.app_gateway_type = 'existing'", "elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: # accept disk name or ID", "availablity zone is not yet \" \"supported. Please use '--location'", "('openlogic', 'centos', '^7.4'), ('coreos', 'coreos', None), ('credativ', 'debian', '-backports'), ('oracle',", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "raise CLIError(err.format(role, ids)) role_id = role_defs[0].id return role_id def process_vm_create_namespace(cmd,", "or not [x for x in (temp.location_info or []) if", "- subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg) # format back to", "in range(min_length, max_length + 1): raise CLIError('The password length must", "'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k:", "16: err = \"instance count '{}' is out of range", "module https://github.com/Azure/azure-cli/issues/5105 def process_msi_namespace(cmd, namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd,", "= urn_match.group(2) namespace.os_sku = urn_match.group(3) namespace.os_version = urn_match.group(4) if not", "\"{}\". Use a custom image name, id, or pick one", "account in target resource group that matches the VM's location", "in enumerate(identities): if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i],", "and vaultCertificate index {2} in arg {3}' if 'certificateUrl' not", "namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and not getattr(namespace, 'attach_os_disk', None):", "resource group namespace.storage_account = account.name namespace.storage_account_type = 'existing' logger.debug(\"suitable existing", "Azure Marketplace image' elif profile == StorageProfile.ManagedSpecializedOSDisk: return 'attach existing", "enough leeway for over-provision factor = 1.5 if over_provision else", "== 'uri': # STORAGE PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif", "error: --source {SNAPSHOT | DISK} | --source VHD_BLOB_URI [--source-storage-account-id ID]'", "namespace.nsg, namespace.resource_group_name, 'Microsoft.Network', 'networkSecurityGroups'): namespace.nsg_type = 'existing' logger.debug(\"using specified NSG", "'new' logger.debug('no suitable subnet found. One will be created.') def", "'getattr' to avoid crash namespace.disk_info = normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks',", "._actions import _get_latest_image_version logger = get_logger(__name__) def validate_asg_names_or_ids(cmd, namespace): from", "'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized storage profile: {}'.format(namespace.storage_profile))", "type (password for Windows, ssh for Linux) by examining the", "image_type == 'image_id': # STORAGE PROFILE #5 namespace.storage_profile = StorageProfile.ManagedCustomImage", "CloudError network_client = get_network_client(cli_ctx) try: return network_client.load_balancers.get(resource_group_name, lb_name) except CloudError:", "= \"'Standard' load balancer is required because 'single placement group'", "--instance-id ID | --size-gb GB') elif bool(namespace.disk) != bool(namespace.instance_id): raise", "[x.lower() for x in new_4core_sizes] if size not in new_4core_sizes:", "vault :return: resource group name or None :rtype: str \"\"\"", "secrets] except Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err))", "than one role matches the given name '{}'. Please pick", "\"\"\" from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client from", "'storage_container_name', 'use_unmanaged_disk', 'storage_sku'] + auth_params _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage:", "validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num = 0", "val, 'resource_group': resource_group, 'namespace': resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) }", "2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using", "data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk) if source_snapshot: namespace.data_snapshots.append(source_snapshot)", "'{}': allowed values: '{}'\".format(sku, allowed_skus)) def _validate_location(cmd, namespace, zone_info, size_info):", "= 12 if len(password) not in range(min_length, max_length + 1):", "x in images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched:", "error: --disk EXIST_DISK --instance-id ID | --size-gb GB') elif bool(namespace.disk)", "Corporation. All rights reserved. # Licensed under the MIT License.", "= parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name) if lb: namespace.load_balancer_type", "= _get_nic_id(cmd.cli_ctx, namespace.primary_nic, rg) def _validate_secrets(secrets, os_type): \"\"\" Validates a", "b, c, d = [int(x) for x in address.split('.')] result", "1 upper case character, 1 number and 1 special character')", "raise CLIError('usage error: --disk EXIST_DISK --instance-id ID | --size-gb GB')", "CLIError(\"Multiple possible values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name,", "2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace): if namespace.accelerated_networking", "[] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden,", "name cannot contain special characters \\/\"[]:|<>+=;,?*@# or ends with .'", "msrestazure.tools import parse_resource_id if namespace.storage_account: storage_id = parse_resource_id(namespace.storage_account) rg =", "pylint: disable=no-member namespace.os_type = vm_info.storage_profile.os_disk.os_type.value namespace.source_virtual_machine = res_id if namespace.data_disk_sources:", "get_target_network_api, get_storage_blob_uri from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.keys as keys", "except Exception as err: raise CLIError('Error decoding secrets: {0}'.format(err)) for", "'Standard_DS11_v2', 'AZAP_Performance_ComputeV17C'] aval_sizes = [x.lower() for x in aval_sizes] if", "namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription'])", "LoadBalancer frontend required = [] forbidden = ['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku',", "offer, sku = namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return", "[--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name,", "error_msg = \"usage error: --subnet-address-prefix value should be a subrange", "namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if", "image in the marketplace # Ubuntu 16.04, SLES 12 SP3,", "subnet_exists: raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: #", "disable=line-too-long if count < 3: raise CLIError('Password must have the", "parse_resource_id(namespace.load_balancer).get('resource_group', namespace.resource_group_name) lb_name = parse_resource_id(namespace.load_balancer)['name'] lb = get_network_lb(cmd.cli_ctx, namespace.resource_group_name, lb_name)", "namespace.keyvault rg = namespace.resource_group_name if rg: if not kv or", "for x in balancer.backend_address_pools] if len(values) > 1: raise CLIError(\"Multiple", "namespace.public_ip_address) elif namespace.public_ip_address == '': namespace.public_ip_address_type = None logger.debug('no public", "values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ', '.join(values)))", "'applicationGateway' if balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways", "string_or_file if public_key_filepath[-4:].lower() == '.pub': private_key_filepath = public_key_filepath[:-4] else: private_key_filepath", "msrestazure.tools import is_valid_resource_id vnet = namespace.vnet_name subnet = namespace.subnet rg", "images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in images", "existing managed OS disk' def _validate_managed_disk_sku(sku): allowed_skus = ['Premium_LRS', 'Standard_LRS',", "gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or []) else: raise", "_compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) vm_info = compute_client.virtual_machines.get(res['resource_group'], res['name']) # pylint: disable=no-member namespace.os_type", "'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] + auth_params else: raise CLIError('Unrecognized", "ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id =", "--image parameter. Updates the namespace and returns the type for", "import MSI_LOCAL_ID for i, _ in enumerate(identities): if identities[i] !=", "if namespace.secrets: _validate_secrets(namespace.secrets, namespace.os_type) if namespace.license_type and namespace.os_type.lower() != 'windows':", "pylint: disable=line-too-long pattern = (r'[\\\\\\/\"\\[\\]:|<>+=;,?*@#()!A-Z]+' if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err", "_get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces', 'Microsoft.Network') def", "vhd based images? if urlparse(namespace.image).scheme: return 'uri' # 4 -", "namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password: raise ValueError('Admin password", "namespace.admin_password: raise ValueError('Admin password cannot be used with SSH authentication", "x: x.publishing_profile.published_date)[-1] else: image_version_info = compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2'])", "for idx, secret in enumerate(narg_secret): if 'sourceVault' not in secret:", "else: namespace.vm_sku = 'Standard_D1_v2' _validate_location(cmd, namespace, namespace.zones, namespace.vm_sku) validate_asg_names_or_ids(cmd, namespace)", "be supplied to SSH Key Value. ' 'You can use", "namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type',", "CLIError('The password length must be between {} and {}'.format(min_length, max_length))", "\"[--admin-username USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try:", "# pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks = [] namespace.data_snapshots", "namespace.storage_profile = StorageProfile.SAPirImage else: # STORAGE PROFILE #4 namespace.storage_profile =", "logger.debug(\"application gateway '%s' not found. It will be created.\", namespace.application_gateway)", "if not namespace.public_ip_per_vm and namespace.vm_domain_name: raise CLIError('Usage error: --vm-domain-name can", "following: 1 lower case character, 1 upper case character, 1", "VHD_BLOB_URI [--source-storage-account-id ID]' try: namespace.source_blob_uri, namespace.source_disk, namespace.source_snapshot = _figure_out_storage_source( cmd.cli_ctx,", "_validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.SAPirImage: required = ['image', 'use_unmanaged_disk'] forbidden", "resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name = namespace.network_security_group_name \\ or", "zonal scale-sets or with\" \" 100+ instances\") def _validate_vmss_create_load_balancer_or_app_gateway(cmd, namespace):", "is None: raise CLIError(\"usage error: '--role {}' is not applicable", "CLI generate one for you') namespace.ssh_key_value = content def _validate_vm_vmss_msi(cmd,", "len(role_defs) > 1: ids = [r.id for r in role_defs]", "= None logger.debug('no application gateway will be used') elif namespace.application_gateway", "for k, v in kwargs.items() if not v} return resource_id(**kwargs)", "is_linux = (os_type.lower() == 'linux') # pylint: disable=line-too-long pattern =", "specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import", "from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val kwargs =", "{0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault' in secret", "urlparse # pylint: disable=import-error from knack.log import get_logger from knack.util", "such locations\".format(namespace.resource_group_name)) # pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False):", "['image', 'os_type', 'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile ==", "CLIError('There is no latest image version exists for \"{}\"'.format(namespace.image)) image_version_info", "specified namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account '%s'\",", "a different value.\".format(username)) return username def _validate_admin_password(password, os_type): import re", "namespace.key_encryption_key: raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault", "import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer and namespace.application_gateway:", "else: try: replica_count = int(parts[1]) except ValueError: raise CLIError(\"usage error:", "image_info = compute_client.images.get(res['resource_group'], res['name']) namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks", "specify image XOR attach-os-disk raise CLIError('incorrect usage: --image IMAGE |", "subscription=get_subscription_id(cmd.cli_ctx)), 'properties': { 'primary': nics_value[0] == n } }) namespace.nics", "import get_subscription_id nics_value = namespace.nics nics = [] if not", "knack.util import CLIError from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict, validate_parameter_set,", "= 'Secret is missing vaultCertificates array or it is empty", "\" \"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No existing", "_get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if bool(namespace.disk) == bool(namespace.size_gb): raise", "type namespace.authentication_type = 'password' \\ if (namespace.os_type.lower() == 'windows' or", "'--location' to specify a capable one. 'az vm list-skus' can", "None def _get_nic_id(cli_ctx, val, resource_group): return _get_resource_id(cli_ctx, val, resource_group, 'networkInterfaces',", "USERNAME] --admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if", "in role_defs] err = \"More than one role matches the", "namespace.storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace)", "namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace,", "in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]: _validate_vm_create_storage_account(cmd, namespace) _validate_vm_create_availability_set(cmd, namespace) _validate_vm_vmss_create_vnet(cmd, namespace) _validate_vm_create_nsg(cmd,", "len([x for x in [contains_lower, contains_upper, contains_digit, contains_special_char] if x])", "namespace.availability_set) def _validate_vm_vmss_create_vnet(cmd, namespace, for_scale_set=False): from msrestazure.tools import is_valid_resource_id vnet", "namespace.nics = nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic =", "re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try: uuid.UUID(role) role_id", "unrecognized image informations \"{}\"'.format(namespace.image)) # pylint: disable=no-member elif namespace.storage_profile ==", "in identities if x != MSI_LOCAL_ID] if user_assigned_identities and not", "way around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int:", "import ResourceType from azure.cli.core.commands.client_factory import get_subscription_id ApplicationSecurityGroup = cmd.get_models('ApplicationSecurityGroup', resource_type=ResourceType.MGMT_NETWORK)", "if namespace.storage_profile in [StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type)", "type='applicationSecurityGroups', name=val ) ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace):", "'^2012-R2')] import re for p, o, s in distros: if", "eq '{}'\".format(role))) if not role_defs: raise CLIError(\"Role '{}' doesn't exist.\".format(role))", "c, d = [int(x) for x in address.split('.')] result =", "'application_gateways') logger.debug(\"using specified existing application gateway '%s'\", namespace.application_gateway) except CloudError:", "# Public-IP SKU is only exposed for VM. VMSS has", "resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard", "namespace) _validate_vmss_create_nsg(cmd, namespace) _validate_vm_vmss_accelerated_networking(cmd.cli_ctx, namespace) _validate_vm_vmss_create_auth(namespace) _validate_vm_vmss_msi(cmd, namespace) if namespace.license_type", "('oracle', 'oracle-linux', '^7.4'), ('MicrosoftWindowsServer', 'WindowsServer', '^2016'), ('MicrosoftWindowsServer', 'WindowsServer', '^2012-R2')] import", "\"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\":", "possible values found for '{0}': {1}\\nSpecify '{0}' \" \"explicitly.\".format(option_name, ',", "name :param str vault_name: name of the key vault :return:", "'new' logger.debug('new public IP address will be created') # Public-IP", "kv and not is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\"", "not role_id: # retrieve role id role_defs = list(client.list(scope, \"roleName", "if is_linux else 123 min_length = 12 if len(password) not", "AZURE_US_GOV_CLOUD if cmd.cli_ctx.cloud.name != AZURE_US_GOV_CLOUD.name: namespace.vm_sku = 'Standard_DS1_v2' else: namespace.vm_sku", "keyvault_usage = CLIError('usage error: [--keyvault NAME --resource-group NAME | --keyvault", "is None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise CLIError('--public-ip-address", "'application_security_groups') ids = [] if names_or_ids == [\"\"] or not", "sku, re.I)): namespace.accelerated_networking = True def _validate_vmss_create_subnet(namespace): if namespace.vnet_type ==", "raise ValueError('Admin password cannot be used with SSH authentication type')", "= namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer,", "else 'linux' from ._vm_utils import normalize_disk_info # attach_data_disks are not", "load_images_from_aliases_doc images = load_images_from_aliases_doc(cmd.cli_ctx) matched = next((x for x in", "for scale-sets with 100+ instances\" else: err = \"'Standard' load", "required = ['os_type', 'attach_os_disk'] forbidden = ['os_disk_name', 'os_caching', 'storage_account', 'storage_container_name',", "or not names_or_ids: return for val in names_or_ids: if not", "# 4 - nothing specified - create a new storage", "= None if urlparse(source).scheme: # a uri? source_blob_uri = source", "# find storage account in target resource group that matches", "p.lower() == publisher and (o is None or o.lower() ==", "namespace): from msrestazure.tools import resource_id from azure.cli.core.commands.client_factory import get_subscription_id nics_value", "if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/', role, re.I): role_id = role else: try: uuid.UUID(role)", "if over_provision else 1 return ((1 << (32 - mask))", "is not yet \" \"supported. Please use '--location' to specify", "windows) :return: errors if any were found :rtype: list \"\"\"", "if namespace.subnet_address_prefix is None: cidr = namespace.vnet_address_prefix.split('/', 1)[0] i =", "_get_resource_id(cmd.cli_ctx, namespace.disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') def validate_vmss_disk(cmd, namespace): if namespace.disk:", "--admin-password PASSWORD\") from knack.prompting import prompt_pass, NoTTYException try: if not", "CLIError(\"usage error: {}'s replica count must be an integer\".format(parts[0])) regions_info.append(TargetRegion(name=parts[0],", "balancer is required for scale-sets with 100+ instances\" else: err", "namespace.nat_pool_name = lb.inbound_nat_pools[0].name logger.debug(\"using specified existing load balancer '%s'\", namespace.load_balancer)", "files '%s' and '%s' have been generated under ~/.ssh to", "\"explicitly.\".format(option_name, ', '.join(values))) elif not values: raise CLIError(\"No existing values", "min_length = 12 if len(password) not in range(min_length, max_length +", "'Standard_F4', 'Standard_F4_ABC', 'Standard_F4s', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D8_v3', 'Standard_D8s_v3'] new_4core_sizes = [x.lower()", "for v in client.list(rg) if v.location == location and v.subnets):", "= 72 if is_linux else 123 min_length = 12 if", "group that matches the VM's location with a matching subnet", "image_data_disks_num = 0 if namespace.storage_profile == StorageProfile.ManagedCustomImage: # extract additional", "logger.debug('no suitable subnet found. One will be created.') def _subnet_capacity_check(subnet_mask,", "def process_assign_identity_namespace(cmd, namespace): _validate_vm_vmss_msi(cmd, namespace, from_set_command=True) def process_remove_identity_namespace(cmd, namespace): if", "range(min_length, max_length + 1): raise CLIError('The password length must be", "'{0}': {1}\\nSpecify '{0}' explicitly.\".format( # pylint: disable=line-too-long '--nat-pool-name', ', '.join([n.name", "'Standard_D8_v3', 'Standard_D8s_v3', 'Standard_D32-8s_v3', 'Standard_E8_v3', 'Standard_E8s_v3', 'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2',", "managed disk image resource compute_client = _compute_client_factory(cmd.cli_ctx) try: compute_client.images.get(namespace.resource_group_name, namespace.image)", "namespace.instance_count, not namespace.disable_overprovision): break if i < 16: err =", "to create the VM/VMSS because availablity zone is not yet", "if namespace.app_gateway_type == 'new': required.append('app_gateway_sku') required.append('app_gateway_capacity') if namespace.vnet_type != 'new':", "endregion # region disk, snapshot, image validators def validate_vm_disk(cmd, namespace):", "['Standard_D3_v2', 'Standard_D12_v2', 'Standard_D3_v2_Promo', 'Standard_D12_v2_Promo', 'Standard_DS3_v2', 'Standard_DS12_v2', 'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo',", "namespace.os_blob_uri, namespace.os_disk, namespace.os_snapshot = _figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long", "= StorageProfile.SACustomImage elif image_type == 'image_id': # STORAGE PROFILE #5", "len(parts) == 1: regions_info.append(TargetRegion(name=parts[0])) else: try: replica_count = int(parts[1]) except", "import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault in client.list():", "type of OS (linux or windows) :return: errors if any", "forbidden = ['os_disk_name', 'os_caching', 'image', 'storage_account', 'storage_container_name', 'data_disk_sizes_gb', 'storage_sku'] +", "result = '{0:08b}{1:08b}{2:08b}{3:08b}'.format(a, b, c, d) return int(result[:-bit_mask_len], 2) error_msg", "from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults for vault", "at secret ' \\ 'index {1} and vaultCertificate index {2}", "subnet found. One will be created.') def _subnet_capacity_check(subnet_mask, vmss_instance_count, over_provision):", "format back to the cidr candaidate_str = '{0:32b}'.format(candidate_int << subnet_bit_mask_len)", "balancer type: {}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name", "at index {0} in arg {1}'.format( idx, idx_arg)) if 'sourceVault'", "result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type =", "\"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\"] if username.lower()", "from azure.cli.core.profiles import ResourceType std_lb_is_available = cmd.supported_api_version(min_api='2017-08-01', resource_type=ResourceType.MGMT_NETWORK) if namespace.load_balancer", "region disk, snapshot, image validators def validate_vm_disk(cmd, namespace): namespace.disk =", "i in range(24, 16, -1): if _subnet_capacity_check(i, namespace.instance_count, not namespace.disable_overprovision):", "Resource_sku doesn't implement location_info property if not hasattr(temp, 'location_info'): return", "\"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\", \"certificateStore\": \"cert store name", "be used\", account.name) else: # 4 - nothing specified -", "== 'latest': image_version = _get_latest_image_version(cmd.cli_ctx, namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku) else:", "namespace.load_balancer_sku is None: namespace.load_balancer_sku = LBSkuName.standard.value logger.debug(\"use Standard sku as", "import get_subscription_id if is_valid_resource_id(val): return val kwargs = { 'name':", "{}'.format(balancer_type)) balancer = client.get(resource_group, balancer_name) values = [x.name for x", "It will be created.\", namespace.application_gateway) elif namespace.application_gateway == '': namespace.app_gateway_type", "appropriate file names: # 'base_name'(with private keys), and 'base_name.pub'(with public", "_get_resource_id(cmd.cli_ctx, namespace.nsg, namespace.resource_group_name, 'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address:", "namespace.application_gateway is None: namespace.app_gateway_type = 'new' logger.debug('new application gateway will", "'%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s' not", "= 'Invalid image \"{}\". Use a custom image name, id,", "based images? if urlparse(namespace.image).scheme: return 'uri' # 4 - attempt", "if not hasattr(temp, 'location_info'): return if not temp or not", "= next( (a for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value ==", "keep 'identity_role' for output as logical name is more readable", "# to refresh the list, run 'az vm create --accelerated-networking", "1): raise CLIError('The password length must be between {} and", "size'\" raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and", "JSON array containing secrets for use in VM Creation Secrets", "namespace.load_balancer_type is None and namespace.app_gateway_type is None: if namespace.public_ip_address: raise", "not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise CLIError(\"usage", "role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone, namespace.size) validate_asg_names_or_ids(cmd,", "try: # try capturing from VM, a most common scenario", "logger.warning(\"Querying the image of '%s' failed for an error '%s'.", "be used') elif namespace.nsg is None: namespace.nsg_type = 'new' logger.debug('new", "root for license information. # -------------------------------------------------------------------------------------------- # pylint:disable=too-many-lines import os", "'windows': raise CLIError('usage error: --license-type is only applicable on Windows", "fully-qualified ID (assumes it is an image ID) if is_valid_resource_id(namespace.image):", "raise CLIError(err.format(namespace.instance_count)) namespace.subnet_address_prefix = '{}/{}'.format(cidr, i) if namespace.app_gateway_type and namespace.app_gateway_subnet_address_prefix", "Associated scaleset will be missing ssh/rdp, so warn here. logger.warning(\"No", "POLICY]') # endregion # region disk, snapshot, image validators def", "from knack.log import get_logger from knack.util import CLIError from azure.cli.core.commands.validators", "image_plan.publisher return 'urn' # 3 - unmanaged vhd based images?", "'disks', 'Microsoft.Compute') for d in namespace.attach_data_disks] if not namespace.os_type: namespace.os_type", "namespace.network_security_group_name \\ or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8)) def validate_keyvault(cmd, namespace): namespace.keyvault", "namespace.single_placement_group = False elif namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should", "namespace.app_gateway_type = 'new' logger.debug(\"application gateway '%s' not found. It will", "OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions import CloudError source_blob_uri", "= _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >> (vnet_bit_mask_len -", "for n in nics_value: nics.append({ 'id': n if '/' in", "resource_namespace, 'type': resource_type, 'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v", "# 3 - nothing specified - find viable storage account", "7.4, CentOS 7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel", "' 'with minimum Compute API version of 2017-12-01') if namespace.identity_scope:", "get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name =", "idx, idx_arg)) if 'sourceVault' in secret and 'id' not in", "run 'az vm create --accelerated-networking --size Standard_DS1_v2' and # get", "off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err = \"'Standard'", "!= MSI_LOCAL_ID] if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'): raise CLIError('usage error:", "ids = [r.id for r in role_defs] err = \"More", "one first and try \" \"again.\".format(option_name)) return values[0] def _validate_vmss_single_placement_group(namespace):", "in images if x['urnAlias'].lower() == namespace.image.lower()), None) if matched: namespace.os_publisher", "[ \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\",", "IP '%s' not found. It will be created.\", namespace.public_ip_address) elif", "CLIError('usage error: --license-type is only applicable on Windows VM') _validate_vm_vmss_msi(cmd,", "if i < 16: err = \"instance count '{}' is", "profile 2017_03_09 balancer_type = 'loadBalancer' if namespace.single_placement_group is not False", "turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err =", "namespace): get_default_location_from_resource_group(cmd, namespace) validate_tags(namespace) def process_gallery_image_version_namespace(cmd, namespace): TargetRegion = cmd.get_models('TargetRegion')", "minimal parameters to resolve the expected storage profile if getattr(namespace,", "is turned off\") elif namespace.load_balancer_sku == LBSkuName.basic.value: if namespace.zones: err", "namespace.identities[i] != MSI_LOCAL_ID: namespace.identities[i] = _get_resource_id(cmd.cli_ctx, namespace.identities[i], namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity')", "parameters validate_parameter_set( namespace, required, forbidden, description='storage profile: {}:'.format(_get_storage_profile_description(namespace.storage_profile))) image_data_disks_num =", "_validate_vm_create_storage_profile(cmd, namespace, for_scale_set=False): from msrestazure.tools import parse_resource_id # use minimal", "rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics',", "namespace='Microsoft.Compute', type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set)", "= namespace.subnet rg = namespace.resource_group_name location = namespace.location nics =", "profile == StorageProfile.SACustomImage: return 'create unmanaged OS disk created from", "None: raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]') def", "namespace.disk_encryption_keyvault = _get_resource_id(cmd.cli_ctx, namespace.disk_encryption_keyvault, namespace.resource_group_name, 'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if", "specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug(\"using specified vnet '%s'", "_parse_image_argument(cmd, namespace) if image_type == 'uri': # STORAGE PROFILE #2", "ID) if is_valid_resource_id(namespace.image): return 'image_id' # 2 - attempt to", "= compute_client.gallery_image_versions.get( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1'], gallery_image_version_name=res['child_name_2']) image_data_disks_num = len(image_version_info.storage_profile.data_disk_images or", "Debian \"Stretch\" with backports kernel # Oracle Linux 7.4, Windows", "for \"{}\"'.format(namespace.image)) image_version_info = sorted(image_version_infos, key=lambda x: x.publishing_profile.published_date)[-1] else: image_version_info", "'storage_container_name', 'use_unmanaged_disk'] if for_scale_set: forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedCustomImage:", "\"incorrect usage for authentication-type 'password': \" \"[--admin-username USERNAME] --admin-password PASSWORD\")", "except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku", "different value.\".format(username)) return username def _validate_admin_password(password, os_type): import re is_linux", "for s in vnet_match.subnets if _check_subnet(s)), None) if not result:", "ResourceType client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_AUTHORIZATION).role_definitions role_id = None if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/',", "namespace): from msrestazure.tools import is_valid_resource_id keyvault_usage = CLIError('usage error: [--keyvault", "file names: # 'base_name'(with private keys), and 'base_name.pub'(with public keys)", "size = getattr(namespace, 'size', None) or getattr(namespace, 'vm_sku', None) size", "# apply default auth type (password for Windows, ssh for", "balancer_name) values = [x.name for x in balancer.backend_address_pools] if len(values)", "CLIError(linux_err if is_linux else win_err) if is_linux and re.findall(r'^[$-]+', username):", "bool(namespace.instance_id): raise CLIError('usage error: --disk EXIST_DISK --instance-id ID') def process_disk_or_snapshot_create_namespace(cmd,", "will be created\", storage_id['name']) else: from azure.cli.core.profiles import ResourceType from", "if v.location == location and v.subnets): # 1 - find", "'Standard_D3_v2_ABC', 'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2',", "{}'.format(min_length, max_length)) contains_lower = re.findall('[a-z]+', password) contains_upper = re.findall('[A-Z]+', password)", "be used') elif namespace.public_ip_address is None: namespace.public_ip_address_type = 'new' logger.debug('new", "if namespace.source: usage_error = 'usage error: --source {SNAPSHOT | DISK}", "PROFILE #2 namespace.storage_profile = StorageProfile.SACustomImage elif image_type == 'image_id': #", "namespace.storage_account_type = 'existing' logger.debug(\"using specified existing storage account '%s'\", storage_id['name'])", "because 'single placement group' is turned off\" raise CLIError('usage error:{}'.format(err))", "and not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]')", "reserved. # Licensed under the MIT License. See License.txt in", "x in (temp.location_info or []) if x.zones]: raise CLIError(\"{}'s location", "ResourceType.MGMT_NETWORK, api_version=get_target_network_api(cli_ctx)) def get_network_lb(cli_ctx, resource_group_name, lb_name): from msrestazure.azure_exceptions import CloudError", "\"please specify '--os-type OS_TYPE'\") def _figure_out_storage_source(cli_ctx, resource_group_name, source): from msrestazure.azure_exceptions", "# pylint: disable=line-too-long if count < 3: raise CLIError('Password must", "\"'Standard' load balancer is required because 'single placement group' is", "[validate_file_or_dict(secret) for secret in secrets] except Exception as err: raise", "normalize_disk_info(image_data_disks_num=image_data_disks_num, data_disk_sizes_gb=namespace.data_disk_sizes_gb, attach_data_disks=getattr(namespace, 'attach_data_disks', []), storage_sku=namespace.storage_sku, os_disk_caching=namespace.os_caching, data_disk_cachings=namespace.data_caching) def _validate_vm_create_storage_account(cmd,", "not values: raise CLIError(\"No existing values found for '{0}'. Create", "not namespace.disable_overprovision): break if i < 16: err = \"instance", "Dict fitting the JSON description above :param string os_type: the", "role_defs[0].id return role_id def process_vm_create_namespace(cmd, namespace): validate_tags(namespace) _validate_location(cmd, namespace, namespace.zone,", "import get_subscription_id vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', subscription=get_subscription_id(cmd.cli_ctx)) namespace.network_security_group_name", "[{ \"sourceVault\": { \"id\": \"value\" }, \"vaultCertificates\": [{ \"certificateUrl\": \"value\",", "create the VM/VMSS because availablity zone is not yet \"", "Validates a parsed JSON array containing secrets for use in", "rg, 'Microsoft.Compute', 'availabilitySets'): raise CLIError(\"Availability set '{}' does not exist.\".format(name))", "at index {0} in ' \\ 'arg {1} ' errors.append(err.format(idx,", "= _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise CLIError(\"Unable to resolve", "# STORAGE PROFILE #6 namespace.storage_profile = StorageProfile.ManagedSpecializedOSDisk elif namespace.image and", "if is_linux else r'[\\\\\\/\"\\[\\]:|<>+=;,?*@]+') linux_err = r'admin user name cannot", "import prompt_pass, NoTTYException try: if not namespace.admin_password: namespace.admin_password = prompt_pass('Admin", "found\", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if", "client = get_network_client(cmd.cli_ctx).virtual_networks # find VNET in target resource group", "index {2} in arg {3}' if 'certificateUrl' not in cert:", "= [] namespace.data_disks = [] namespace.data_snapshots = [] if namespace.data_disk_sources:", "location_info property if not hasattr(temp, 'location_info'): return if not temp", "if identities[i] != MSI_LOCAL_ID: identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name, 'userAssignedIdentities',", "raise CLIError(\"Incorrect usage '--key-encryption-keyvault': \" \"'--key-encryption-key' is required\") namespace.key_encryption_keyvault =", "were found :rtype: list \"\"\" is_windows = os_type == 'windows'", "if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower()", "IP address will be created') # Public-IP SKU is only", "res_id if namespace.data_disk_sources: raise CLIError(\"'--data-disk-sources' is not allowed when capturing", "# 2 - params for new storage account specified namespace.storage_account_type", "used with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path", "nic_ids if hasattr(namespace, 'primary_nic') and namespace.primary_nic: namespace.primary_nic = _get_nic_id(cmd.cli_ctx, namespace.primary_nic,", "= _compute_client_factory(cli_ctx) # pylint: disable=no-member try: info = compute_client.snapshots.get(resource_group_name, source)", "if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg = parse_resource_id(namespace.application_gateway).get( 'resource_group',", "if not role_id: # retrieve role id role_defs = list(client.list(scope,", "forbidden.append('os_disk_name') _validate_managed_disk_sku(namespace.storage_sku) elif namespace.storage_profile == StorageProfile.ManagedSpecializedOSDisk: required = ['os_type', 'attach_os_disk']", "identity\") # keep 'identity_role' for output as logical name is", "max_length = 72 if is_linux else 123 min_length = 12", "inbound nat pool was configured on '%s'\", namespace.load_balancer) else: namespace.nat_pool_name", "balancer_type == 'applicationGateway': if namespace.application_gateway: client = get_network_client(cmd.cli_ctx).application_gateways try: rg", "'Standard_DS13-4_v2', 'Standard_DS14-4_v2', 'Standard_DS3_v2_Promo', 'Standard_DS12_v2_Promo', 'Standard_DS13-4_v2_Promo', 'Standard_DS14-4_v2_Promo', 'Standard_F4', 'Standard_F4s', 'Standard_D8_v3', 'Standard_D8s_v3',", "'WindowsServer', '^2012-R2')] import re for p, o, s in distros:", "required = ['image', 'use_unmanaged_disk'] forbidden = ['os_type', 'attach_os_disk', 'data_disk_sizes_gb'] elif", "int(result[:-bit_mask_len], 2) error_msg = \"usage error: --subnet-address-prefix value should be", "is None: namespace.public_ip_address_type = 'new' logger.debug('new public IP address will", "if size_info is None or size_info.number_of_cores < 8: return #", "balancer '%s'\", namespace.load_balancer) else: namespace.load_balancer_type = 'new' logger.debug(\"load balancer '%s'", "_figure_out_storage_source( cmd.cli_ctx, namespace.resource_group_name, data_disk_source) if source_blob_uri: namespace.data_blob_uris.append(source_blob_uri) if source_disk: namespace.data_disks.append(source_disk)", "source_disk = source elif '/snapshots/' in source.lower(): source_snapshot = source", "'vaults', 'Microsoft.KeyVault') if namespace.key_encryption_keyvault: if not namespace.key_encryption_key: raise CLIError(\"Incorrect usage", "apply default auth type (password for Windows, ssh for Linux)", "= _get_resource_id( cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks',", "nothing specified - find viable storage account in target resource", "== [\"\"] or not names_or_ids: return for val in names_or_ids:", "= _get_nic_id(cmd.cli_ctx, namespace.nic, namespace.resource_group_name) def validate_vm_nics(cmd, namespace): rg = namespace.resource_group_name", "namespace.vnet_type = 'existing' logger.debug(\"existing vnet '%s' and subnet '%s' found\",", "in new_4core_sizes: compute_client = _compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info =", "'Standard_LRS' if for_scale_set else 'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and", "namespace.nic_type = 'existing' namespace.public_ip_address_type = None logger.debug('existing NIC(s) will be", "not exist.\".format(subnet)) elif subnet_exists: # 2 - user specified existing", "count '{}' is out of range of 2^16 subnet size'\"", "secrets: {0}'.format(err)) for idx_arg, narg_secret in enumerate(loaded_secret): for idx, secret", "logger.debug('no NSG will be used') elif namespace.nsg is None: namespace.nsg_type", "and not namespace.image: if namespace.use_unmanaged_disk: # STORAGE PROFILE #3 namespace.storage_profile", "None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools import", "namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now verify that", "network_client.load_balancers.get(resource_group_name, lb_name) except CloudError: return None def process_vmss_create_namespace(cmd, namespace): validate_tags(namespace)", ") ids.append(ApplicationSecurityGroup(id=val)) setattr(namespace, 'application_security_groups', ids) def validate_nsg_name(cmd, namespace): from msrestazure.tools", "to match an URN alias (most likely) from azure.cli.command_modules.vm._actions import", "for a in storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location", "resource_type=ResourceType.MGMT_NETWORK) if namespace.public_ip_sku == PublicIPAddressSkuName.standard.value: if not namespace.public_ip_address_allocation: namespace.public_ip_address_allocation =", "import re # 1 - check if a fully-qualified ID", "err = \"'Standard' load balancer is required because 'single placement", "namespace.disable_overprovision) result = next((s for s in vnet_match.subnets if _check_subnet(s)),", "with SSH authentication type') validate_ssh_key(namespace) if not namespace.ssh_dest_key_path: namespace.ssh_dest_key_path =", "'attach to existing unmanaged OS disk' elif profile == StorageProfile.ManagedCustomImage:", "CLIError('usage error: --license-type is only applicable on Windows VM scaleset')", "namespace, zone_info, size_info): from ._vm_utils import list_sku_info if not namespace.location:", "a, b, c, d = [int(x) for x in address.split('.')]", "urllib.parse import urlparse except ImportError: from urlparse import urlparse #", "# 4 - attempt to match an URN alias (most", "namespace.os_type = image_info.storage_profile.os_disk.os_type.value image_data_disks_num = len(image_info.storage_profile.data_disks or []) elif res['type'].lower()", "= 'windows' if 'windows' in namespace.os_offer.lower() else 'linux' from ._vm_utils", "import re for p, o, s in distros: if p.lower()", "namespace.storage_profile == StorageProfile.ManagedCustomImage: required = ['image'] forbidden = ['os_type', 'attach_os_disk',", "if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None: raise", "= subnet_cidr.split('/') subnet_bit_mask_len = 32 - int(mask) if vnet_bit_mask_len <=", "'use_unmanaged_disk'] forbidden = ['attach_os_disk', 'data_disk_sizes_gb'] elif namespace.storage_profile == StorageProfile.SASpecializedOSDisk: required", "for r in role_defs] err = \"More than one role", "_figure_out_storage_source(cmd.cli_ctx, namespace.resource_group_name, namespace.source) # pylint: disable=line-too-long namespace.data_blob_uris = [] namespace.data_disks", "StorageProfile.ManagedCustomImage elif image_type == 'urn': if namespace.use_unmanaged_disk: # STORAGE PROFILE", "def _validate_secrets(secrets, os_type): \"\"\" Validates a parsed JSON array containing", "= namespace.os_version image = compute_client.virtual_machine_images.get(namespace.location, namespace.os_publisher, namespace.os_offer, namespace.os_sku, image_version) #", "string_or_file) with open(string_or_file, 'r') as f: content = f.read() elif", "namespace.assign_identity is not None: identities = namespace.assign_identity or [] from", "_get_default_address_pool(cli_ctx, resource_group, balancer_name, balancer_type): option_name = '--backend-pool-name' client = getattr(get_network_client(cli_ctx),", "store name (only on windows)\" }] }] :param dict secrets:", "around if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise", "retrieve role id role_defs = list(client.list(scope, \"roleName eq '{}'\".format(role))) if", "cmd.cli_ctx, namespace.attach_os_disk, namespace.resource_group_name, 'disks', 'Microsoft.Compute') if getattr(namespace, 'attach_data_disks', None): if", "created') if namespace.load_balancer_type == 'new' and namespace.single_placement_group is False and", "errors.append(message.format('certificateUrl', idx, jdx, idx_arg)) if is_windows and 'certificateStore' not in", "'--scope'/'--role' is only applicable when assign system identity\") # keep", "name = as_id['name'] rg = as_id.get('resource_group', namespace.resource_group_name) if not check_existence(cmd.cli_ctx,", "to verify the defaults we are coming out vnet_ip_address, mask", "StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type: raise", "'Standard_D12_v2_ABC', 'Standard_F4_ABC', 'Standard_F8s_v2', 'Standard_D4_v2', 'Standard_D13_v2', 'Standard_D4_v2_Promo', 'Standard_D13_v2_Promo', 'Standard_DS4_v2', 'Standard_DS13_v2', 'Standard_DS14-8_v2',", "storage_client.list_by_resource_group(namespace.resource_group_name) if a.sku.tier.value == sku_tier and a.location == namespace.location), None)", "STORAGE PROFILE #4 namespace.storage_profile = StorageProfile.ManagedPirImage else: raise CLIError('Unrecognized image", "is_valid_resource_id(kv): raise keyvault_usage def _get_resource_group_from_vault_name(cli_ctx, vault_name): \"\"\" Fetch resource group", "return _subnet_capacity_check(subnet_mask, namespace.instance_count, not namespace.disable_overprovision) result = next((s for s", "_check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1]", "prompt_pass('Admin Password: ', confirm=True) except NoTTYException: raise CLIError('Please specify password", "'%s'\", namespace.nsg) else: namespace.nsg_type = 'new' logger.debug(\"specified NSG '%s' not", "return values[0] def _validate_vmss_single_placement_group(namespace): if namespace.platform_fault_domain_count is not None and", "is turned off\" raise CLIError('usage error:{}'.format(err)) def get_network_client(cli_ctx): from azure.cli.core.profiles", "in secret and 'id' not in secret['sourceVault']: errors.append( 'Secret is", "import get_mgmt_service_client from msrestazure.tools import parse_resource_id client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_KEYVAULT).vaults", "def validate_ssh_key(namespace): string_or_file = (namespace.ssh_key_value or os.path.join(os.path.expanduser('~'), '.ssh', 'id_rsa.pub')) content", "\\ if (namespace.os_type.lower() == 'windows' or namespace.admin_password) else 'ssh' if", "{ 'primary': nics_value[0] == n } }) namespace.nics = nics", "100+ instances\" else: err = \"'Standard' load balancer is required", "not in [x.lower() for x in allowed_skus]: raise CLIError(\"invalid storage", "if not namespace.os_type: raise CLIError(\"usage error: os type is required", "= image_info.os_type.value gallery_image_version = res.get('child_name_2', '') if gallery_image_version.lower() in ['latest',", "= result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug(\"existing vnet", "namespace.resource_group_name, 'userAssignedIdentities', 'Microsoft.ManagedIdentity') # TODO move to its own command", "disable=no-member return image.plan except CloudError as ex: logger.warning(\"Querying the image", "for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics = nic_ids", "matched['sku'] namespace.os_version = matched['version'] return 'urn' # 5 - check", "ID (assumes it is an image ID) if is_valid_resource_id(namespace.image): return", "meets the general requirements, but is specifically disallowed for this", "required = ['os_type', 'attach_os_disk', 'use_unmanaged_disk'] forbidden = ['os_disk_name', 'os_caching', 'image',", "4 - nothing specified - create a new storage account", "return None def _get_resource_id(cli_ctx, val, resource_group, resource_type, resource_namespace): from msrestazure.tools", "namespace.os_publisher, namespace.os_offer, namespace.os_sku if not publisher: return publisher, offer, sku", "logger.debug('no public IP address will be used') elif namespace.public_ip_address is", "with the required/forbidden parameters for VM if namespace.storage_profile == StorageProfile.ManagedPirImage:", "rights reserved. # Licensed under the MIT License. See License.txt", "if bool(namespace.disk) == bool(namespace.size_gb): raise CLIError('usage error: --disk EXIST_DISK --instance-id", "next((s for s in vnet_match.subnets if _check_subnet(s)), None) if not", "if not namespace.storage_sku and namespace.storage_profile in [StorageProfile.SAPirImage, StorageProfile.SACustomImage]: # pylint:", "'Premium_LRS' if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled", "type='availabilitySets', name=name) logger.debug(\"adding to specified availability set '%s'\", namespace.availability_set) def", "getattr(namespace, 'attach_os_disk', None): image_type = _parse_image_argument(cmd, namespace) if image_type ==", "[StorageProfile.ManagedSpecializedOSDisk, StorageProfile.SASpecializedOSDisk]: return namespace.admin_username = _validate_admin_username(namespace.admin_username, namespace.os_type) if not namespace.os_type:", "in namespace.storage_sku else 'Standard' account = next( (a for a", "- unmanaged vhd based images? if urlparse(namespace.image).scheme: return 'uri' #", "mask)) - 2) > int(vmss_instance_count * factor) def _validate_vm_vmss_accelerated_networking(cli_ctx, namespace):", "validate proper arguments supplied based on the authentication type if", "validate password _validate_admin_password(namespace.admin_password, namespace.os_type) elif namespace.authentication_type == 'ssh': if namespace.admin_password:", "namespace): TargetRegion = cmd.get_models('TargetRegion') if namespace.target_regions: regions_info = [] for", "and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled = True # Now verify", "username def _validate_admin_password(password, os_type): import re is_linux = (os_type.lower() ==", "if namespace.storage_sku == 'UltraSSD_LRS' and namespace.ultra_ssd_enabled is None: namespace.ultra_ssd_enabled =", "not namespace.priority: raise CLIError('Usage error: --priority PRIORITY [--eviction-policy POLICY]') #", "_get_resource_id(cmd.cli_ctx, namespace.source, namespace.resource_group_name, 'virtualMachines', 'Microsoft.Compute') res = parse_resource_id(res_id) compute_client =", "'Standard_F8', 'Standard_F8s', 'Standard_M64-16ms', 'Standard_D16_v3', 'Standard_D16s_v3', 'Standard_D32-16s_v3', 'Standard_D64-16s_v3', 'Standard_E16_v3', 'Standard_E16s_v3', 'Standard_E32-16s_v3',", "namespace): from msrestazure.tools import resource_id, is_valid_resource_id from azure.cli.core.profiles import ResourceType", "# extract vnet information needed to verify the defaults we", "namespace.plan_name = image_plan.name namespace.plan_product = image_plan.product namespace.plan_publisher = image_plan.publisher return", "'networkSecurityGroups', 'Microsoft.Network') def _validate_vm_vmss_create_public_ip(cmd, namespace): if namespace.public_ip_address: if check_existence(cmd.cli_ctx, namespace.public_ip_address,", "CLIError(err.format(namespace.image, [x['urnAlias'] for x in images])) def _get_image_plan_info_if_exists(cmd, namespace): from", "is None: if namespace.public_ip_address: raise CLIError('--public-ip-address can only be used", "account: # 3 - nothing specified - find viable storage", "namespace.single_placement_group: raise CLIError(\"usage error: '--single-placement-group' should be turned off for", "'subscription': get_subscription_id(cli_ctx) } missing_kwargs = {k: v for k, v", "raise CLIError(\"Subnet '{}' does not exist.\".format(subnet)) elif subnet_exists: # 2", "namespace.os_offer = matched['offer'] namespace.os_sku = matched['sku'] namespace.os_version = matched['version'] return", "forbidden = ['nat_pool_name', 'load_balancer', 'health_probe'] validate_parameter_set(namespace, required, forbidden, description='network balancer:", "[] for n in namespace.nics: nic_ids.append(_get_nic_id(cmd.cli_ctx, n, rg)) namespace.nics =", "the key vault :return: resource group name or None :rtype:", "custom image res = parse_resource_id(namespace.image) compute_client = _compute_client_factory(cmd.cli_ctx, subscription_id=res['subscription']) if", "getattr(namespace, 'attach_data_disks', None): if not namespace.use_unmanaged_disk: namespace.attach_data_disks = [_get_resource_id(cmd.cli_ctx, d,", "['app_gateway_subnet_address_prefix', 'application_gateway', 'app_gateway_sku', 'app_gateway_capacity'] validate_parameter_set(namespace, required, forbidden, description='network balancer: load", "profile == StorageProfile.ManagedPirImage: return 'create managed OS disk from Azure", "_compute_client_factory(cli_ctx) sizes = compute_client.virtual_machine_sizes.list(namespace.location) size_info = next((s for s in", "\"'Standard' load balancer is required for zonal scale-sets\" elif namespace.instance_count", "created') def _validate_vmss_create_nsg(cmd, namespace): if namespace.nsg: namespace.nsg = _get_resource_id(cmd.cli_ctx, namespace.nsg,", "['latest', '']: image_version_infos = compute_client.gallery_image_versions.list_by_gallery_image( resource_group_name=res['resource_group'], gallery_name=res['name'], gallery_image_name=res['child_name_1']) image_version_infos =", "CLIError(error_msg) candidate_int = _convert_to_int(subnet_ip_address, subnet_bit_mask_len) + 1 if (candidate_int >>", "if namespace.load_balancer_type is None and namespace.app_gateway_type is None: if namespace.public_ip_address:", "os_type): import re if not username: raise CLIError(\"admin user name", "7.4, CoreOS Linux, Debian \"Stretch\" with backports kernel # Oracle", "'--subnet' usage: --subnet SUBNET_ID | \" \"--subnet SUBNET_NAME --vnet-name VNET_NAME\")", "process_vmss_create_namespace(cmd, namespace): validate_tags(namespace) if namespace.vm_sku is None: from azure.cli.core.cloud import", "if (candidate_int >> (vnet_bit_mask_len - subnet_bit_mask_len)) > vnet_int: raise CLIError(error_msg)", "allowed_skus = ['Premium_LRS', 'Standard_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'] if sku and sku.lower()", "used when creating a new load ' 'balancer or application", "else: raise CLIError('An RSA key file or key value must" ]
[ "FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in", ": ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1", "for i in range(0, len(text)): # print(answer[i], ' isSpace :", "print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ',", "range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if", "'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions)", "else : if whitespaceCount != 0: whitespaceCount = 0 def", "print(\"LINK : \", link) http = httplib2.Http() status, html =", "start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1],", "questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions)", "open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = []", "answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as", "return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question)", "answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag =", "i in range(0, questionCount): print('Q: ', questions[i]) if i ==", "text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0", "whitespaceCount + 1 if whitespaceCount >= 3: # print(0 +", "# print(answerLength) for i in range(0, answerLength): # print(answer[i], '", "answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3:", "len(answer) whitespaceCount = 0 # print(answerLength) for i in range(0,", "\" End : \", end) soup1 = BeautifulSoup(bodyText[start : end],", "i in range(0, len(text)): # print(answer[i], ' isSpace : ',", "+ i - 3) return answer[0 : 0 + i", "answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link)", "print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount =", "answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled :", "soup = BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)')))", "blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK", "http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions =", "in range(0, len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace())", "print('Q: ', questions[i]) if i == questionCount - 1: #Last", "answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions)", "= getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList", "for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList", "len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList =", "import re import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil", "return text[0 : 0 + i - 2] else :", "= 0 # print(answerLength) for i in range(0, len(text)): #", "- 3) return answer[0 : 0 + i - 2].lstrip()", "as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i", "# print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return", "getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText,", "+ i - 2]) return text[0 : 0 + i", "removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \", link)", "processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList # link", "\", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1)", "+ i - 2] else : if whitespaceCount != 0:", "answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled", "i in range(0, answerLength): # print(answer[i], ' isSpace : ',", "soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList", "# print(0 + i - 3) return answer[0 : 0", "link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link,", "questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions,", "= 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0", "questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList =", "i - 3) return answer[0 : 0 + i -", "def getAnswers(body, questions): bodyText = body.getText() # answerTag = getAnswerTag(body,", ", \" End : \", end) soup1 = BeautifulSoup(bodyText[start :", "print(\"Start : \", start , \" End : \", end)", "bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start, -1)", "cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return", "# answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount =", "text[0 : 0 + i - 2] else : if", "- 2].lstrip() else : if whitespaceCount != 0: whitespaceCount =", "i - 2] else : if whitespaceCount != 0: whitespaceCount", "print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions", "3: # print(0 + i - 3) return answer[0 :", "= [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def", "removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS,", "stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER,", "0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText", "' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount", "ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions)", "-1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i", "text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3:", "', questions[i]) if i == questionCount - 1: #Last element", "= convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList, \"output.txt\") saveToMongo(faqJsonList, COLLECTION_NAME)", "# print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList", "in range(0, questionCount): print('Q: ', questions[i]) if i == questionCount", "__name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n')", "0 # print(answerLength) for i in range(0, len(text)): # print(answer[i],", "link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__==", "html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body", "= getAnswers(body, questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\"", "!= 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions):", "', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if", "1: #Last element answer = getLastAnswer(questions[i], bodyText) else : start", "= soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return", "= FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions,", "0 + i - 2]) return text[0 : 0 +", "\", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions()", "in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start =", "print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount =", "import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList,", "def getFaqOfLink(link): # print(\"LINK : \", link) http = httplib2.Http()", ": 0 + i - 2] else : if whitespaceCount", "return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): #", "import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import", "questionCount = len(questions) answerList = [] for i in range(0,", "# print(\"LINK : \", link) http = httplib2.Http() status, html", "', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER)", "i - 2]) return text[0 : 0 + i -", "if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions)", "else : if whitespaceCount != 0: whitespaceCount = 0 return", "= len(answer) whitespaceCount = 0 # print(answerLength) for i in", "answerList = getAnswers(body, questions) return questions, answerList # link =", "if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def", ": \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions =", "3) return answer[0 : 0 + i - 2].lstrip() else", ": \", start , \" End : \", end) soup1", "0 + i - 2] else : if whitespaceCount !=", "0 + i - 2].lstrip() else : if whitespaceCount !=", "= body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText)", "answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for i", "+ i - 2].lstrip() else : if whitespaceCount != 0:", "return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList", "questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r')", "FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i in range(0,", "soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer =", "= [] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i]", "= len(questions) answerList = [] for i in range(0, questionCount):", "<reponame>ednihs-yahska/unibrowser import re import httplib2 from bs4 import BeautifulSoup from", "# print(text[0 : 0 + i - 2]) return text[0", "questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText) else", "= checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER ==", "checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False:", "answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount", "BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer", "body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList", "questions) # print(bodyText) questionCount = len(questions) answerList = [] for", "2].lstrip() else : if whitespaceCount != 0: whitespaceCount = 0", "bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end =", "with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList =", "cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength) for", "3) # print(text[0 : 0 + i - 2]) return", ": 0 + i - 2]) return text[0 : 0", "isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount +", "in range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace())", "body.getText() # answerTag = getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount", "# link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if", "\", link) http = httplib2.Http() status, html = http.request(link) soup", "getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \",", ": \", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') #", "-1) print(\"Start : \", start , \" End : \",", "ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question", "faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link =", "print(0 + i - 3) return answer[0 : 0 +", "\"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with", "# isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if", "answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace():", "print('A: ', answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled =", "answerList = [] for i in range(0, questionCount): print('Q: ',", "[] for i in range(0, questionCount): print('Q: ', questions[i]) if", "range(0, answerLength): # print(answer[i], ' isSpace : ', answer[i].isspace()) if", "questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList)", "if answer[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >=", "answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount", "False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link):", "answer[0 : 0 + i - 2].lstrip() else : if", "+ len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount", "end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer", "- 2] else : if whitespaceCount != 0: whitespaceCount =", "= bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start", "getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS", "isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount +", "2] else : if whitespaceCount != 0: whitespaceCount = 0", "= whitespaceCount + 1 if whitespaceCount >= 3: # print(0", "import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = [] for", "= myfile.read().split('\\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)):", "# print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in", "import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra,", "'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer)", ": ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount = whitespaceCount + 1", ">= 3: # print(0 + i - 3) return answer[0", ": start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i +", "getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList, \"output.txt\")", "questions[i]) if i == questionCount - 1: #Last element answer", "for i in range(0, answerLength): # print(answer[i], ' isSpace :", "BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions)", "= getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList,", "2]) return text[0 : 0 + i - 2] else", "bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions) #", "# print(answer[i], ' isSpace : ', answer[i].isspace()) if answer[i].isspace(): whitespaceCount", "+ len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start", "whitespaceCount >= 3: # print(0 + i - 3) return", "print(0 + i - 3) # print(text[0 : 0 +", "0 # print(answerLength) for i in range(0, answerLength): # print(answer[i],", "print(answerLength) for i in range(0, answerLength): # print(answer[i], ' isSpace", "whitespaceCount >= 3: # print(0 + i - 3) #", "1 if whitespaceCount >= 3: # print(0 + i -", "else : start = bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i", "FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList)", "for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText):", "whitespaceCount = whitespaceCount + 1 if whitespaceCount >= 3: #", "questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) +", "!= 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer)", "= getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile:", "0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() #", "= BeautifulSoup(html, 'html.parser') body = soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) #", "# print(0 + i - 3) # print(text[0 : 0", "= \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" # questions, answerList = getFaqOfLink(link) if __name__== \"__main__\":", ": if whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip()", "soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body,", "print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions, answerList #", "return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText() # answerTag", "element answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i])", ": if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer):", "1], start, -1) print(\"Start : \", start , \" End", "if i == questionCount - 1: #Last element answer =", "# print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount", "def cleanQuestions(questions): questionList = [] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip()))", "status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body =", "bodyText.index(questions[i + 1], start, -1) print(\"Start : \", start ,", "' isSpace : ', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount", "for i in range(0, questionCount): print('Q: ', questions[i]) if i", "removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME", "whitespaceCount = 0 # print(answerLength) for i in range(0, len(text)):", "answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer)", "bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength)", "\", start , \" End : \", end) soup1 =", ": 0 + i - 2].lstrip() else : if whitespaceCount", "== questionCount - 1: #Last element answer = getLastAnswer(questions[i], bodyText)", "whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength =", "isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER == False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions,", "+ i - 3) # print(text[0 : 0 + i", "'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for", "questionCount): print('Q: ', questions[i]) if i == questionCount - 1:", "from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from", "def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 # print(answerLength)", "end = bodyText.index(questions[i + 1], start, -1) print(\"Start : \",", "= cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return", "def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \",", "cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions): #", "len(text)): # print(answer[i], ' isSpace : ', answer[i].isspace()) if text[i].isspace():", "= httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser')", "= getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK :", ">= 3: # print(0 + i - 3) # print(text[0", "0: whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount", "#Last element answer = getLastAnswer(questions[i], bodyText) else : start =", "getAnswerTag(body, bodyText, questions) # print(bodyText) questionCount = len(questions) answerList =", "print(questions) def getFaqOfLink(link): # print(\"LINK : \", link) http =", ": -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for", "link) http = httplib2.Http() status, html = http.request(link) soup =", "print(answerLength) for i in range(0, len(text)): # print(answer[i], ' isSpace", "from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList =", "0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount = 0 #", "i - 3) # print(text[0 : 0 + i -", "[] for question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question,", "answer = cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def", "in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link)", "= BeautifulSoup(bodyText[start : end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip()", "return answer[0 : 0 + i - 2].lstrip() else :", "cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList = getAnswers(body, questions) return questions,", "getFaqOfLink(link): # print(\"LINK : \", link) http = httplib2.Http() status,", "answer) return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) #", "= [] for i in range(0, questionCount): print('Q: ', questions[i])", "- 2]) return text[0 : 0 + i - 2]", "End : \", end) soup1 = BeautifulSoup(bodyText[start : end], 'html.parser')", "= bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() #", "\"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList", "removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text", "bodyText, questions) # print(bodyText) questionCount = len(questions) answerList = []", "= bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount = 0 #", "len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip()) whitespaceCount =", "questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start = bodyText.index(question)", "getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text = bodyText[start", "len(questions[i]) end = bodyText.index(questions[i + 1], start, -1) print(\"Start :", ": \", link) http = httplib2.Http() status, html = http.request(link)", "bodyText): start = bodyText.index(question) + len(question) text = bodyText[start :", "answer = getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) +", "print(bodyText) questionCount = len(questions) answerList = [] for i in", "+ 1 if whitespaceCount >= 3: # print(0 + i", "getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i]) end", "questions, answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList)", "', answer[i].isspace()) if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if", "= 0 # print(answerLength) for i in range(0, answerLength): #", ": end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer =", "start , \" End : \", end) soup1 = BeautifulSoup(bodyText[start", "bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions,", "= 0 return answer.rstrip() def getAnswers(body, questions): bodyText = body.getText()", "# print(bodyText) questionCount = len(questions) answerList = [] for i", "getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def", "= bodyText.index(questions[i]) + len(questions[i]) end = bodyText.index(questions[i + 1], start,", "saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList", "getAnswers(body, questions) return questions, answerList # link = \"https://transportation.oregonstate.edu/aabc/frequently-asked-questions\" #", "[] for i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions,", "myfile: FAQ_LINKS = myfile.read().split('\\n') faqJsonList = [] for i in", "whitespaceCount = 0 def cleanAnswer(answer): answerLength = len(answer) whitespaceCount =", "+ 1], start, -1) print(\"Start : \", start , \"", "return answerList def processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled", "jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) # saveJsonToFile(faqJsonList, \"output.txt\") saveToMongo(faqJsonList,", "i in range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList =", "processWithCustomQuestions(questions): # isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled)", "bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip() # print(text.lstrip())", "start, -1) print(\"Start : \", start , \" End :", "= cleanAnswer(answer) answerList.append(answer) print('A: ', answer) return answerList def processWithCustomQuestions(questions):", "- 3) # print(text[0 : 0 + i - 2])", "# questions, answerList = getFaqOfLink(link) if __name__== \"__main__\": with open(FAQ_LINKS,", "start = bodyText.index(question) + len(question) text = bodyText[start : -1].lstrip()", "myfile.read().split('\\n') faqJsonList = [] for i in range(0, len(FAQ_LINKS)): link", "3: # print(0 + i - 3) # print(text[0 :", "blackListedQuestions) print(questions) def getFaqOfLink(link): # print(\"LINK : \", link) http", "answerList = getFaqOfLink(link) jsonList = convertToJsonList(link, questions, answerList) faqJsonList.extend(jsonList) #", "BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo", "range(0, len(FAQ_LINKS)): link = FAQ_LINKS[i] questions, answerList = getFaqOfLink(link) jsonList", "httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates,", "scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions, getBlackListedQuestions, convertToJsonList, saveToMongo from scraping.Constants", "httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html, 'html.parser') body", "scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions): questionList = []", "print(text.lstrip()) whitespaceCount = 0 # print(answerLength) for i in range(0,", "whitespaceCount = 0 # print(answerLength) for i in range(0, answerLength):", "convertToJsonList, saveToMongo from scraping.Constants import ENABLE_CUSTOM_QUESTIONS_FILTER, FAQ_LINKS, COLLECTION_NAME def cleanQuestions(questions):", "isCustomQuestionsEnabled = checkConfigForFlag(ENABLE_CUSTOM_QUESTIONS_FILTER) # print(\"isCustomQuestionsEnabled : \", isCustomQuestionsEnabled) if ENABLE_CUSTOM_QUESTIONS_FILTER", "# print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer) answerList.append(answer) print('A:", "= getLastAnswer(questions[i], bodyText) else : start = bodyText.index(questions[i]) + len(questions[i])", "http = httplib2.Http() status, html = http.request(link) soup = BeautifulSoup(html,", "i == questionCount - 1: #Last element answer = getLastAnswer(questions[i],", "# print(answerLength) for i in range(0, len(text)): # print(answer[i], '", "whitespaceCount != 0: whitespaceCount = 0 return answer.rstrip() def getAnswers(body,", "= soup.body questions = cleanQuestions(soup(text=re.compile(r'\\s*((?:how|How|Can|can|what|What|where|Where|describe|Describe|Who|who|When|when|Why|why|Should|should|is|Is|I|Do|do|Are|are|Will|will)[^.<>?]*?\\s*\\?)'))) # print(questions) processWithCustomQuestions(questions) answerList =", "if whitespaceCount >= 3: # print(0 + i - 3)", "question in questions: questionList.append(stripExtra(question.lstrip().rstrip())) return removeDuplicates(questionList) def getLastAnswer(question, bodyText): start", "if __name__== \"__main__\": with open(FAQ_LINKS, 'r') as myfile: FAQ_LINKS =", "end], 'html.parser') # print(soup1) answer = soup1.getText().lstrip() answer = cleanAnswer(answer)", "COLLECTION_NAME def cleanQuestions(questions): questionList = [] for question in questions:", "range(0, questionCount): print('Q: ', questions[i]) if i == questionCount -", "== False: return blackListedQuestions = getBlackListedQuestions() removeBlackListedQuestions(questions, blackListedQuestions) print(questions) def", "re import httplib2 from bs4 import BeautifulSoup from scraping.faqscrapperutil import", "if whitespaceCount != 0: whitespaceCount = 0 def cleanAnswer(answer): answerLength", "from bs4 import BeautifulSoup from scraping.faqscrapperutil import stripExtra, removeDuplicates, removeBlackListedQuestions,", "def getLastAnswer(question, bodyText): start = bodyText.index(question) + len(question) text =", "- 1: #Last element answer = getLastAnswer(questions[i], bodyText) else :", "if text[i].isspace(): whitespaceCount = whitespaceCount + 1 if whitespaceCount >=", "= http.request(link) soup = BeautifulSoup(html, 'html.parser') body = soup.body questions", "print(text[0 : 0 + i - 2]) return text[0 :", "questions): bodyText = body.getText() # answerTag = getAnswerTag(body, bodyText, questions)", "len(questions) answerList = [] for i in range(0, questionCount): print('Q:", "i - 2].lstrip() else : if whitespaceCount != 0: whitespaceCount", "whitespaceCount = 0 return answer.rstrip() def getAnswers(body, questions): bodyText =" ]
[ "\"\"\"Presents a yes/no prompt to the user and handles replies.", "readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no", "text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable", "= dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\",", "for key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\",", "text with ANSI escape codes to achieve the desired look.", "A message string to present before confirmation. Returns: True if", "\"\\x01%s\\x02\" % text codes = [] if color: codes.append(FG_COLORS[color]) if", "dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ),", "if the user confirmed the prompt; else False. \"\"\" replies", "attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes to achieve", "archives. Creates colored text and helps write Messages output. \"\"\"", "before confirmation. Returns: True if the user confirmed the prompt;", "attr in attrs) if not escape: esc = lambda n:", "\";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text codes =", "+ 10) for key, val in FG_COLORS.items()) ATTRIBUTES = dict(", "dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\",", "string with the original text wrapped by escape codes. \"\"\"", "\"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try:", "the original text wrapped by escape codes. \"\"\" def sgr(*codes):", "contextmanager import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\",", "prompt; else False. \"\"\" replies = { \"yes\": True, \"no\":", "\"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text", "\"\"\" from contextlib import contextmanager import itertools import readline FG_COLORS", "with readline_disabled(): print(text) while reply not in replies: try: reply", "features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents", "\"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None,", "confirmation. Returns: True if the user confirmed the prompt; else", "True to escape invisibles (for readline); else False. Returns: A", "\"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val", "replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply =", "\"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10)))", "98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key, val", "escape codes to achieve the desired look. Args: color: The", "\"\" with readline_disabled(): print(text) while reply not in replies: try:", "\"\"\"Terminal utilities specific to message archives. Creates colored text and", "colored text and helps write Messages output. \"\"\" from contextlib", "def esc(text): return \"\\x01%s\\x02\" % text codes = [] if", "\" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply =", "helps write Messages output. \"\"\" from contextlib import contextmanager import", "} prompt = \"%s (yes/no): \" % colored(\"Are you sure?\",", "FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\",", "if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape:", "Creates colored text and helps write Messages output. \"\"\" from", "% (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to", "temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True)", "sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text)", "input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\" print(reply) return replies[reply]", "text: A message string to present before confirmation. Returns: True", "range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text", "else False. Returns: A string with the original text wrapped", "\"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS =", "if not escape: esc = lambda n: n return \"%s%s%s\"", "{ \"yes\": True, \"no\": False, } prompt = \"%s (yes/no):", "\"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1,", "= input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\" print(reply) return", "to the user and handles replies. Args: text: A message", "in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\",", "codes)) def esc(text): return \"\\x01%s\\x02\" % text codes = []", "\"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def", "\"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\",", "yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to", "specific to message archives. Creates colored text and helps write", "codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def", "True if the user confirmed the prompt; else False. \"\"\"", "reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\" print(reply)", "range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\",", "reply not in replies: try: reply = input(prompt).casefold() except (EOFError,", "\"\"\" replies = { \"yes\": True, \"no\": False, } prompt", "escape: True to escape invisibles (for readline); else False. Returns:", "\"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\",", "codes to achieve the desired look. Args: color: The foreground", "\"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10)", "while reply not in replies: try: reply = input(prompt).casefold() except", "colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape", "on_color: The background color. attrs: A list of effects. escape:", "by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str,", "BG_COLORS = dict((f\"on_{key}\", val + 10) for key, val in", "not escape: esc = lambda n: n return \"%s%s%s\" %", "readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text):", "readline_disabled(): print(text) while reply not in replies: try: reply =", "escape invisibles (for readline); else False. Returns: A string with", "\"\"\"Wraps text with ANSI escape codes to achieve the desired", "color. on_color: The background color. attrs: A list of effects.", "utilities specific to message archives. Creates colored text and helps", "Returns: A string with the original text wrapped by escape", "% \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" % text codes", "def readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\"", "attrs) if not escape: esc = lambda n: n return", "color: The foreground color. on_color: The background color. attrs: A", "reply = \"\" with readline_disabled(): print(text) while reply not in", "val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\",", "if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs)", "in replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply", "look. Args: color: The foreground color. on_color: The background color.", "range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for key,", "\"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None,", "text codes = [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color])", "\"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text, color=None,", "The background color. attrs: A list of effects. escape: True", "disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def", "a yes/no prompt to the user and handles replies. Args:", "and handles replies. Args: text: A message string to present", "attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text) while reply", "user confirmed the prompt; else False. \"\"\" replies = {", "\"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ), range(1, 10))) def colored(text,", "\"strikethrough\", ), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False):", "prompt to the user and handles replies. Args: text: A", "import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\",", "yes/no prompt to the user and handles replies. Args: text:", "string to present before confirmation. Returns: True if the user", "original text wrapped by escape codes. \"\"\" def sgr(*codes): return", "False. Returns: A string with the original text wrapped by", "attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape: esc", "A list of effects. escape: True to escape invisibles (for", "from contextlib import contextmanager import itertools import readline FG_COLORS =", "user and handles replies. Args: text: A message string to", "for attr in attrs) if not escape: esc = lambda", "\"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\",", "try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt): reply = \"no\"", "to achieve the desired look. Args: color: The foreground color.", "\"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\",", "message archives. Creates colored text and helps write Messages output.", "def confirm(text): \"\"\"Presents a yes/no prompt to the user and", "escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes))", "\"\"\" def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text):", "\"yes\": True, \"no\": False, } prompt = \"%s (yes/no): \"", "else False. \"\"\" replies = { \"yes\": True, \"no\": False,", "of effects. escape: True to escape invisibles (for readline); else", "wrapped by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\" %", "present before confirmation. Returns: True if the user confirmed the", "not in replies: try: reply = input(prompt).casefold() except (EOFError, KeyboardInterrupt):", "list of effects. escape: True to escape invisibles (for readline);", "escape=False): \"\"\"Wraps text with ANSI escape codes to achieve the", "<gh_stars>0 \"\"\"Terminal utilities specific to message archives. Creates colored text", "in attrs) if not escape: esc = lambda n: n", "the user confirmed the prompt; else False. \"\"\" replies =", "confirmed the prompt; else False. \"\"\" replies = { \"yes\":", "to escape invisibles (for readline); else False. Returns: A string", "color. attrs: A list of effects. escape: True to escape", "10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with", "prompt = \"%s (yes/no): \" % colored(\"Are you sure?\", \"red\",", "return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context", "return \"\\x01%s\\x02\" % text codes = [] if color: codes.append(FG_COLORS[color])", "esc = lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text,", "the user and handles replies. Args: text: A message string", "(for readline); else False. Returns: A string with the original", "FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\",", "n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled():", "foreground color. on_color: The background color. attrs: A list of", "to message archives. Creates colored text and helps write Messages", "codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if not", "message string to present before confirmation. Returns: True if the", "with ANSI escape codes to achieve the desired look. Args:", "text and helps write Messages output. \"\"\" from contextlib import", "\"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val +", "import contextmanager import itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\",", "text wrapped by escape codes. \"\"\" def sgr(*codes): return \"\\x1b[%sm\"", "codes.extend(ATTRIBUTES[attr] for attr in attrs) if not escape: esc =", "38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ),", "= lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0)))", "escape=True) reply = \"\" with readline_disabled(): print(text) while reply not", "desired look. Args: color: The foreground color. on_color: The background", "colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with", "False. \"\"\" replies = { \"yes\": True, \"no\": False, }", "import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\",", "ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\",", "= dict( zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\",", "background color. attrs: A list of effects. escape: True to", "effects. escape: True to escape invisibles (for readline); else False.", "False, } prompt = \"%s (yes/no): \" % colored(\"Are you", "\"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\",", "True, \"no\": False, } prompt = \"%s (yes/no): \" %", "with the original text wrapped by escape codes. \"\"\" def", "write Messages output. \"\"\" from contextlib import contextmanager import itertools", "% colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\"", "Messages output. \"\"\" from contextlib import contextmanager import itertools import", "zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90,", "zip((\"bold\", \"faint\", \"italic\", \"underline\", \"slow_blink\", \"rapid_blink\", \"reverse\", \"conceal\", \"strikethrough\", ),", "key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\", \"faint\", \"italic\",", "esc(text): return \"\\x01%s\\x02\" % text codes = [] if color:", "escape: esc = lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)),", "readline_disabled(): \"\"\"Context manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False)", "finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to the", "attrs: A list of effects. escape: True to escape invisibles", "color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr", "[] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr]", "return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\" %", "to present before confirmation. Returns: True if the user confirmed", "the prompt; else False. \"\"\" replies = { \"yes\": True,", "\"%s (yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True)", "print(text) while reply not in replies: try: reply = input(prompt).casefold()", "color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes", "if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for", "handles replies. Args: text: A message string to present before", "\"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\",", "(esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily", "= \"%s (yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"],", "on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI escape codes to", "itertools import readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\",", "replies. Args: text: A message string to present before confirmation.", "contextlib import contextmanager import itertools import readline FG_COLORS = dict(itertools.chain(", "\"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98)))) BG_COLORS", "output. \"\"\" from contextlib import contextmanager import itertools import readline", "The foreground color. on_color: The background color. attrs: A list", "replies = { \"yes\": True, \"no\": False, } prompt =", "Args: text: A message string to present before confirmation. Returns:", "dict((f\"on_{key}\", val + 10) for key, val in FG_COLORS.items()) ATTRIBUTES", "= dict((f\"on_{key}\", val + 10) for key, val in FG_COLORS.items())", "readline FG_COLORS = dict(itertools.chain( zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\",", "sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return \"\\x01%s\\x02\"", "10) for key, val in FG_COLORS.items()) ATTRIBUTES = dict( zip((\"bold\",", "on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in attrs) if", "% text codes = [] if color: codes.append(FG_COLORS[color]) if on_color:", "lambda n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager", "n: n return \"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def", "\"%s%s%s\" % (esc(sgr(*codes)), text, esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager", "esc(sgr(0))) @contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable readline", "manager to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield", "readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt to the user", "\"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\", \"bright_white\", ), range(90, 98))))", "achieve the desired look. Args: color: The foreground color. on_color:", "\"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)),", "), range(1, 10))) def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps", "ANSI escape codes to achieve the desired look. Args: color:", "to temporarily disable readline features. \"\"\" readline.set_auto_history(False) try: yield finally:", "def sgr(*codes): return \"\\x1b[%sm\" % \";\".join(map(str, codes)) def esc(text): return", "invisibles (for readline); else False. Returns: A string with the", "= { \"yes\": True, \"no\": False, } prompt = \"%s", "zip((\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30,", "\"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\", ), range(30, 38)), zip((\"bright_black\",", "def colored(text, color=None, on_color=None, attrs=None, escape=False): \"\"\"Wraps text with ANSI", "@contextmanager def readline_disabled(): \"\"\"Context manager to temporarily disable readline features.", "= [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs:", "), range(90, 98)))) BG_COLORS = dict((f\"on_{key}\", val + 10) for", "), range(30, 38)), zip((\"bright_black\", \"bright_red\", \"bright_green\", \"bright_yellow\", \"bright_blue\", \"bright_magenta\", \"bright_cyan\",", "codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if attrs: codes.extend(ATTRIBUTES[attr] for attr in", "codes = [] if color: codes.append(FG_COLORS[color]) if on_color: codes.append(BG_COLORS[on_color]) if", "you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled():", "Returns: True if the user confirmed the prompt; else False.", "(yes/no): \" % colored(\"Are you sure?\", \"red\", attrs=[\"bold\"], escape=True) reply", "\"\"\" readline.set_auto_history(False) try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a", "= \"\" with readline_disabled(): print(text) while reply not in replies:", "try: yield finally: readline.set_auto_history(True) def confirm(text): \"\"\"Presents a yes/no prompt", "confirm(text): \"\"\"Presents a yes/no prompt to the user and handles", "val + 10) for key, val in FG_COLORS.items()) ATTRIBUTES =", "readline); else False. Returns: A string with the original text", "and helps write Messages output. \"\"\" from contextlib import contextmanager", "A string with the original text wrapped by escape codes.", "\"no\": False, } prompt = \"%s (yes/no): \" % colored(\"Are", "\"red\", attrs=[\"bold\"], escape=True) reply = \"\" with readline_disabled(): print(text) while", "Args: color: The foreground color. on_color: The background color. attrs:", "the desired look. Args: color: The foreground color. on_color: The" ]
[ "tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape):", "limitations under the License. import unittest import torch import torch.nn", "W and D (2, 1, 32, 16, 8), ] conv_block", "the pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args:", "[ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16,", "for inch in range(1, 5): for dim in range(1, 4):", "in range(1, 5): for dim in range(1, 4): for factor", "8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV,", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "5): for dim in range(1, 4): for factor in range(1,", "*([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [", "factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2,", "*([8] * dim)), (2, inch, *([8 * factor] * dim)),", "W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\":", "12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\":", "component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0]", "distributed under the License is distributed on an \"AS IS\"", "the specific language governing permissions and # limitations under the", "for H and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA", "{\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "4), # different size for H and W (2, 2,", "nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1,", "torch import torch.nn as nn from parameterized import parameterized from", "= [] for inch in range(1, 5): for dim in", "* dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\":", "W and D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA)", "# type: ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args,", "2020 - 2021 MONAI Consortium # Licensed under the Apache", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "[] for inch in range(1, 5): for dim in range(1,", "inch, *([8] * dim)), (2, inch, *([8 * factor] *", "except in compliance with the License. # You may obtain", "] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4,", "sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict =", "factor}, (2, inch, *([8] * dim)), (2, inch, *([8 *", "] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\":", "test back with the pad/pool sequential component omitted for tests", "16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch in range(1,", "(2, 1, 16, 8, 4), # different size for H,", "Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1)", "conv_block}, (2, 1, 16, 8, 4), # different size for", "SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "# different size for H, W and D (2, 1,", "import parameterized from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample", "you may not use this file except in compliance with", "of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "language governing permissions and # limitations under the License. import", "unittest import torch import torch.nn as nn from parameterized import", "tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore", "TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the", "torch.nn as nn from parameterized import parameterized from monai.networks import", "32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4,", "def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net):", "in range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch,", "3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\":", "input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape))", "use this file except in compliance with the License. #", "2, \"scale_factor\": 3}, (2, 2, 8, 4), # different size", "dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2,", "= [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1,", "for H, W and D (2, 1, 32, 16, 8),", "stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1,", "range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\":", "TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param)", "{\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] *", "\"scale_factor\": 3}, (2, 2, 8, 4), # different size for", "a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless", "CONDITIONS OF ANY KIND, either express or implied. # See", "\"scale_factor\": factor}, (2, inch, *([8] * dim)), (2, inch, *([8", ") TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2,", "2, 8, 4), # different size for H and W", "permissions and # limitations under the License. import unittest import", "8, 4), # different size for H, W and D", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "* factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\":", "and D (2, 1, 32, 16, 8), ] conv_block =", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "Consortium # Licensed under the Apache License, Version 2.0 (the", "License, Version 2.0 (the \"License\"); # you may not use", "for factor in range(1, 3): test_case = [ {\"dimensions\": dim,", "1, \"scale_factor\": 2}, (2, 1, 16, 8, 4), # different", "[ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2,", "License. import unittest import torch import torch.nn as nn from", "# You may obtain a copy of the License at", "in range(1, 4): for factor in range(1, 3): test_case =", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "\"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8, 4), #", "omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] #", "import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for", "1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add", "factor in range(1, 3): test_case = [ {\"dimensions\": dim, \"in_channels\":", "dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)),", "4), # different size for H, W and D (2,", "http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to", "under the License is distributed on an \"AS IS\" BASIS,", "governing permissions and # limitations under the License. import unittest", "tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"] = False", "input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result =", "License for the specific language governing permissions and # limitations", "] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with", "monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = []", "with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__ ==", "from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories", "eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__ == \"__main__\":", "8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back", "# add every test back with the pad/pool sequential component", "[ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8]", "import Conv TEST_CASE_SUBPIXEL = [] for inch in range(1, 5):", "args: dict = tests[0] # type: ignore args = dict(args)", "@parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with", "kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\":", "list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore args =", "type: ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1],", "24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1,", "D (2, 1, 32, 16, 8), ] conv_block = nn.Sequential(", "H and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA =", "range(1, 5): for dim in range(1, 4): for factor in", "= [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2, inch,", "import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv", "the License for the specific language governing permissions and #", "copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required", "the License. import unittest import torch import torch.nn as nn", "2021 MONAI Consortium # Licensed under the Apache License, Version", "size for H and W (2, 2, 24, 12), ]", "(the \"License\"); # you may not use this file except", "at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or", "Apache License, Version 2.0 (the \"License\"); # you may not", "= nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3,", "under the License. import unittest import torch import torch.nn as", "# you may not use this file except in compliance", "3}, (2, 2, 8, 4), # different size for H", "TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2,", "either express or implied. # See the License for the", "from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL =", "- 2021 MONAI Consortium # Licensed under the Apache License,", "padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\":", "OR CONDITIONS OF ANY KIND, either express or implied. #", "(2, inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA", "\"in_channels\": inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)), (2,", "with the pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL):", "nn from parameterized import parameterized from monai.networks import eval_mode from", "TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the pad/pool sequential", "in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type: ignore args", "class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net =", "16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1),", "the License is distributed on an \"AS IS\" BASIS, #", "Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [", "in compliance with the License. # You may obtain a", "Conv TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): for", "test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor}, (2,", "\"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4), # different", "obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #", "different size for H, W and D (2, 1, 32,", "add every test back with the pad/pool sequential component omitted", "software # distributed under the License is distributed on an", "TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\":", "(2, 1, 32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV,", "every test back with the pad/pool sequential component omitted for", "range(1, 4): for factor in range(1, 3): test_case = [", "parameterized import parameterized from monai.networks import eval_mode from monai.networks.blocks import", "eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL", "TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2,", "\"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4), #", "for tests in list(TEST_CASE_SUBPIXEL): args: dict = tests[0] # type:", "and # limitations under the License. import unittest import torch", "back with the pad/pool sequential component omitted for tests in", "= dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase):", "3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) )", "= tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"] =", "(2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3,", "net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape)", "# limitations under the License. import unittest import torch import", "monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from monai.networks.layers.factories import", "expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape,", "Copyright 2020 - 2021 MONAI Consortium # Licensed under the", "Version 2.0 (the \"License\"); # you may not use this", "ignore args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]])", "may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0", "law or agreed to in writing, software # distributed under", "from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch in", "32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every", "= False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self,", "8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA = [ {\"dimensions\": 3,", "3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16,", "for dim in range(1, 4): for factor in range(1, 3):", "3): test_case = [ {\"dimensions\": dim, \"in_channels\": inch, \"scale_factor\": factor},", "1, 16, 8, 4), # different size for H, W", "* dim)), (2, inch, *([8 * factor] * dim)), ]", "implied. # See the License for the specific language governing", "\"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8,", "size for H, W and D (2, 1, 32, 16,", "= SubpixelUpsample(**input_param) with eval_mode(net): result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"License\"); # you may not use this file except in", "TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape,", "4): for factor in range(1, 3): test_case = [ {\"dimensions\":", "License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law", "1, \"scale_factor\": 2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4),", "pad/pool sequential component omitted for tests in list(TEST_CASE_SUBPIXEL): args: dict", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "as nn from parameterized import parameterized from monai.networks import eval_mode", "SubpixelUpsample from monai.networks.layers.factories import Conv TEST_CASE_SUBPIXEL = [] for inch", "2, \"conv_block\": conv_block}, (2, 1, 16, 8, 4), # different", "2}, (2, 1, 16, 8, 4), # different size for", "# Copyright 2020 - 2021 MONAI Consortium # Licensed under", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "from parameterized import parameterized from monai.networks import eval_mode from monai.networks.blocks", "args = dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class", "] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2},", "and W (2, 2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA =", "conv_block = nn.Sequential( Conv[Conv.CONV, 3](1, 4, kernel_size=1), Conv[Conv.CONV, 3](4, 8,", "3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8, 4),", "dim in range(1, 4): for factor in range(1, 3): test_case", "inch in range(1, 5): for dim in range(1, 4): for", "False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param,", "and D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA)", "the License. # You may obtain a copy of the", "for the specific language governing permissions and # limitations under", "TEST_CASE_SUBPIXEL = [] for inch in range(1, 5): for dim", "= [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2,", "(2, 2, 8, 4), # different size for H and", "tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def test_subpixel_shape(self, input_param, input_shape, expected_shape): net", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) # add every test back with the pad/pool", "to in writing, software # distributed under the License is", "dict = tests[0] # type: ignore args = dict(args) args[\"apply_pad_pool\"]", "import unittest import torch import torch.nn as nn from parameterized", "2, 24, 12), ] TEST_CASE_SUBPIXEL_3D_EXTRA = [ {\"dimensions\": 3, \"in_channels\":", "{\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2}, (2, 1, 16, 8,", "16, 8, 4), # different size for H, W and", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL) def", "the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable", "dict(args) args[\"apply_pad_pool\"] = False TEST_CASE_SUBPIXEL.append([args, tests[1], tests[2]]) class TestSUBPIXEL(unittest.TestCase): @parameterized.expand(TEST_CASE_SUBPIXEL)", "1, 32, 16, 8), ] conv_block = nn.Sequential( Conv[Conv.CONV, 3](1,", "You may obtain a copy of the License at #", "\"conv_block\": conv_block}, (2, 1, 16, 8, 4), # different size", "# different size for H and W (2, 2, 24,", "MONAI Consortium # Licensed under the Apache License, Version 2.0", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "import torch import torch.nn as nn from parameterized import parameterized", "different size for H and W (2, 2, 24, 12),", "{\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4),", "# http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA =", "result = net.forward(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) if __name__ == \"__main__\": unittest.main()", "import torch.nn as nn from parameterized import parameterized from monai.networks", "with the License. # You may obtain a copy of", "dim)), (2, inch, *([8 * factor] * dim)), ] TEST_CASE_SUBPIXEL.append(test_case)", "this file except in compliance with the License. # You", "\"scale_factor\": 2}, (2, 1, 16, 8, 4), # different size", "H, W and D (2, 1, 32, 16, 8), ]", "4, kernel_size=1), Conv[Conv.CONV, 3](4, 8, kernel_size=3, stride=1, padding=1) ) TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA", "2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8, 4), #", "the Apache License, Version 2.0 (the \"License\"); # you may", "(2, inch, *([8] * dim)), (2, inch, *([8 * factor]", "8, 4), # different size for H and W (2,", "= [ {\"dimensions\": 3, \"in_channels\": 1, \"scale_factor\": 2, \"conv_block\": conv_block},", "TEST_CASE_SUBPIXEL.append(test_case) TEST_CASE_SUBPIXEL_2D_EXTRA = [ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3},", "D (2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA)", "test_subpixel_shape(self, input_param, input_shape, expected_shape): net = SubpixelUpsample(**input_param) with eval_mode(net): result", "inch, \"scale_factor\": factor}, (2, inch, *([8] * dim)), (2, inch,", "(2, 1, 32, 16, 8), ] TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_2D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_3D_EXTRA) TEST_CASE_SUBPIXEL.append(TEST_CASE_SUBPIXEL_CONV_BLOCK_EXTRA) #", "[ {\"dimensions\": 2, \"in_channels\": 2, \"scale_factor\": 3}, (2, 2, 8,", "parameterized from monai.networks import eval_mode from monai.networks.blocks import SubpixelUpsample from" ]
[ "auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg', 'pdf')", "'./auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg =", "CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg", "import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py')", "userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg =", "CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg", "= CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg',", "'./auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg',", "from staticfg import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg =", "CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf')", "CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg', 'pdf') #auctionEventCfg.build_visual('auctionEventCfg.pdf', 'pdf')", "staticfg import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py',", "= CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py')", "<filename>gen-cfg.py from staticfg import CFGBuilder userCfg = CFGBuilder().build_from_file('user.py', './auction/user.py') bidCfg", "bidCfg = CFGBuilder().build_from_file('bid.py', './auction/bid.py') auctionCfg = CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py')", "= CFGBuilder().build_from_file('auction.py','./auction/auction.py') #auctionEventCfg = CFGBuilder().build_from_file('auction_event.py','./auction/auction_event.py') bidCfg.build_visual('bidCfg', 'pdf') auctionCfg.build_visual('auctionCfg', 'pdf') #auctionEventCfg.build_visual('auctionEventCfg.pdf'," ]
[ "<filename>CodeForces/A2OJ Ladder/softuni_problem.py total_budget = 0 while True: destination = input()", "if command == \"End\": break money = float(command) total_budget +=", "Ladder/softuni_problem.py total_budget = 0 while True: destination = input() if", "== \"End\": break minimal_budget = float(input()) while True: command =", "command = input() if command == \"End\": break money =", "True: command = input() if command == \"End\": break money", "destination == \"End\": break minimal_budget = float(input()) while True: command", "total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget = 0 break", "while True: destination = input() if destination == \"End\": break", "0 while True: destination = input() if destination == \"End\":", "break minimal_budget = float(input()) while True: command = input() if", "float(input()) while True: command = input() if command == \"End\":", "True: destination = input() if destination == \"End\": break minimal_budget", "float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going to", "total_budget = 0 while True: destination = input() if destination", "+= money if total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget", "\"End\": break minimal_budget = float(input()) while True: command = input()", "= 0 while True: destination = input() if destination ==", "if destination == \"End\": break minimal_budget = float(input()) while True:", "= input() if destination == \"End\": break minimal_budget = float(input())", "money = float(command) total_budget += money if total_budget >= minimal_budget:", "destination = input() if destination == \"End\": break minimal_budget =", "if total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget = 0", "while True: command = input() if command == \"End\": break", "\"End\": break money = float(command) total_budget += money if total_budget", "total_budget += money if total_budget >= minimal_budget: print(f\"Going to {destination}!\")", "input() if command == \"End\": break money = float(command) total_budget", "= float(command) total_budget += money if total_budget >= minimal_budget: print(f\"Going", "break money = float(command) total_budget += money if total_budget >=", "= float(input()) while True: command = input() if command ==", "== \"End\": break money = float(command) total_budget += money if", "= input() if command == \"End\": break money = float(command)", "command == \"End\": break money = float(command) total_budget += money", "input() if destination == \"End\": break minimal_budget = float(input()) while", "minimal_budget = float(input()) while True: command = input() if command", "money if total_budget >= minimal_budget: print(f\"Going to {destination}!\") total_budget =" ]
[ "from footmark.regioninfo import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram", "an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None):", "id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection, name, id,", "name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection, name,", "connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection,", "RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def __init__(self, connection=None,", "class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def __init__(self,", "def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection", "Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection", "\"\"\" Represents an ram Region \"\"\" def __init__(self, connection=None, name=None,", "RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\" def", "import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region \"\"\"", "\"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import", "connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo, self).__init__(connection, name, id, RAMConnection)", "footmark.regioninfo import RegionInfo class RAMRegionInfo(RegionInfo): \"\"\" Represents an ram Region", "Represents an ram Region \"\"\" def __init__(self, connection=None, name=None, id=None,", "ram Region \"\"\" def __init__(self, connection=None, name=None, id=None, connection_cls=None): from", "__init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.ram.connection import RAMConnection super(RAMRegionInfo," ]
[ "if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application)", "\"\"\" Convert a single histogram to a D3PO plot :param", "os.chdir(path) while True: try: PORT = randrange(8000, 9000) server =", "pass print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread", "None: subset = s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\"", "def save_histogram(plot, index): \"\"\" Convert a single histogram to a", "can be exported to D3PO. Raises an exception if not", "taken pass print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate()", "fixed; bottom: 0; right: 0; } </style> <!-- not to", "from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] =", "Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application,", "session must have only one dataset open, and 0 or", "subset is not None and s is not subset: return", "returns None \"\"\" result = [] for page in application.viewers:", "= str(label) result['caption'] = 'Generated by Glue' # style settings", "def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory')", "type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body> </html>", "names=[c.label for c in data.components]) for i, subset in enumerate(subsets):", "id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\">", "subset: return None if subset is None: subset = s", "launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view an exported", "server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown", "# data.csv make_data_file(data, subsets, path) # states.json result = {}", "of plot on the page :type index: int :rtype: json-serializable", "if subset is None: subset = s result.append(subset) return tuple(result)", "result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive,", "\" \"and histogram plots\") if sum(len(tab) for tab in application.viewers)", "import SimpleHTTPRequestHandler from random import randrange from socket import error", "If more than one subset is used per stage/tab, returns", "server.allow_reuse_address = True server.server_bind() break except error: # port already", "try: PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler,", "for viewer in page: for layer_artist in viewer.layers: if not", "<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom:", "index): result = {} result['gridPosition'] = [0, index] return result", "tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \" \"and histogram", "html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\">", "= application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export only", "histogram plots\") if sum(len(tab) for tab in application.viewers) == 0:", "for c in data.components]) for i, subset in enumerate(subsets): if", "TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from", "a server to view an exported D3PO bundle, and open", "\"\"\" dc = application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO", "plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on the", "indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with open(html_path,", "result def save_plot_base(plot, index): result = {} result['gridPosition'] = [0,", "scatter plots or histograms are present - At least one", "= {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle']", "D3PO plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param", ":class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on the page", "% i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True):", "type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'>", "charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head>", "result = {} # layout settings result['grid'] = {'nRows': 1,", "not subset: return None if subset is None: subset =", "one plot is present :param application: Glue appication to save", "data.csv make_data_file(data, subsets, path) # states.json result = {} result['filename']", "save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min),", "bundle. Currently, this has the following restrictions: - The Glue", "for tab in application.viewers) == 0: raise ValueError(\"D3PO Export requires", "PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent", ":rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] =", "= 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label,", "glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import", "save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot,", "\"\"\"Save a Glue session to a D3PO bundle. Currently, this", "</head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div>", "and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data =", "result def stage_subsets(application): \"\"\" Return a tuple of the subset", "<meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\"", "to save in. Will be created if needed \"\"\" if", "an application can be exported to D3PO. Raises an exception", "if subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' %", "of data viewers to save :param label: Tab label \"\"\"", "sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w')", "Export requires at least one scatterplot \" \"or histogram\") if", "range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w')", "More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json',", "dict(unselected=unselected) if subset is not None: s = subset.style selected", "in application.viewers: for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())):", "\"\"\" from astropy.table import Table, Column data_path = os.path.join(path, 'data.csv')", "os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data", "not isinstance(s, Subset): continue if subset is not None and", "no subset If more than one subset is used per", "randrange from socket import error import webbrowser from threading import", "glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass", "import Subset DISPATCH = {} def save_page(page, page_number, label, subset):", "used per stage/tab, returns None \"\"\" result = [] for", "import Table, Column data_path = os.path.join(path, 'data.csv') t = Table([data[c]", "of the subset to use for each stage/tab, or None", "range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log", "in data.components]) for i, subset in enumerate(subsets): if subset is", "astropy.table import Table, Column data_path = os.path.join(path, 'data.csv') t =", "\"\"\" Convert a single glue scatter plot to a D3PO", "if sum(len(tab) for tab in application.viewers) == 0: raise ValueError(\"D3PO", "color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i'", "int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type']", "settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2,", "ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer]", "if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path)", "'data.csv'); } ); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt", ":param path: Path to directory to save in. Will be", "restrictions: - The Glue session must have only one dataset", "import webbrowser from threading import Thread os.chdir(path) while True: try:", "= subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected']", "Planet Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script>", "or 1 subsets visible \" \"in each tab\") def make_data_file(data,", "histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot", "information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv');", "exported D3PO bundle, and open a browser. :param path: The", "result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' %", "None if the tab has no subset If more than", "return result def stage_subsets(application): \"\"\" Return a tuple of the", "% data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path", "'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) # show the", "<script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body>", "<div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\">", "import Thread os.chdir(path) while True: try: PORT = randrange(8000, 9000)", "plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D", "def save_scatter(plot, index): \"\"\" Convert a single glue scatter plot", "= True server.server_bind() break except error: # port already taken", "<script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\">", "save :param label: Tab label \"\"\" result = {} #", "glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter", "stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to 0 or", "import os import json from glue.core import Subset DISPATCH =", "setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML", "exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html>", "has the following restrictions: - The Glue session must have", "index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)])", "raise ValueError(\"D3PO Export restricted to 0 or 1 subsets visible", "in. Will be created if needed \"\"\" if os.path.exists(path) and", "Return a tuple of the subset to use for each", "in application.viewers: subset = None for viewer in page: for", "--> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script>", "Export only supports a single dataset\") for tab in application.viewers:", "open, and 0 or 1 subsets - Only scatter plots", "os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) # show", "dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX", "Column data_path = os.path.join(path, 'data.csv') t = Table([data[c] for c", "<!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script", "each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result def", "data.components]) for i, subset in enumerate(subsets): if subset is None:", "\"in each tab\") def make_data_file(data, subsets, path): \"\"\" Create the", "data.components], names=[c.label for c in data.components]) for i, subset in", "to view an exported D3PO bundle, and open a browser.", "= stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets, path)", "be confused with Planet Telex --> <!-- Javscript dependencies -->", "float(plot.state.y_max)]) # XXX log scales return result def save_histogram(plot, index):", "rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer {", "/ 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not", "a browser. :param path: The TLD of the bundle \"\"\"", "from random import randrange from socket import error import webbrowser", "<head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\"", "is not None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize", "if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to 0", "result = {} result['filename'] = 'data.csv' # XXX don't think", "index: 1D index of plot on the page :type index:", "is None: subset = s result.append(subset) return tuple(result) def can_save_d3po(application):", "subset): \"\"\" Convert a tab of a glue session into", "glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from socket import", "= result['markerStyle'] # save each plot result['plots'] = list(map(save_plot, page,", "to directory to save in. Will be created if needed", "size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type':", "= {} result['gridPosition'] = [0, index] return result def save_plot(plot,", "range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result def", "json from glue.core import Subset DISPATCH = {} def save_page(page,", "{} def save_page(page, page_number, label, subset): \"\"\" Convert a tab", "= dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) #", ":type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of plot on", "launch=True): \"\"\"Save a Glue session to a D3PO bundle. Currently,", "open(html_path, 'w') as outfile: outfile.write(HTML) # show the result if", "tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports", "None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path,", "% page_number} result['histogramStyle'] = result['markerStyle'] # save each plot result['plots']", "tuple of subsets \"\"\" from astropy.table import Table, Column data_path", "error import webbrowser from threading import Thread os.chdir(path) while True:", "scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on", "Export restricted to 0 or 1 subsets visible \" \"in", "viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer if not", "the data.csv file, given Data and tuple of subsets \"\"\"", "from threading import Thread os.chdir(path) while True: try: PORT =", "\"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] =", "Table, Column data_path = os.path.join(path, 'data.csv') t = Table([data[c] for", "= s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether", ":param path: The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver", "state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result,", "\" \"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export", "subset is used per stage/tab, returns None \"\"\" result =", "os import json from glue.core import Subset DISPATCH = {}", "save_d3po(application, path, launch=True): \"\"\"Save a Glue session to a D3PO", "\"\"\" Create the data.csv file, given Data and tuple of", "'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path", "page, range(len(page)))) return result def save_plot_base(plot, index): result = {}", "result def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index)", "D3PO. Raises an exception if not \"\"\" dc = application.session.data_collection", "result['markerStyle'] # save each plot result['plots'] = list(map(save_plot, page, range(len(page))))", "has no subset If more than one subset is used", "id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div", "layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] =", "None and s is not subset: return None if subset", "from astropy.table import Table, Column data_path = os.path.join(path, 'data.csv') t", "Convert a single histogram to a D3PO plot :param plot:", "layer_artist.layer if not isinstance(s, Subset): continue if subset is not", "data.csv file, given Data and tuple of subsets \"\"\" from", "\"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not os.path.exists(path):", "HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" />", "plots or histograms are present - At least one plot", "in data.components], names=[c.label for c in data.components]) for i, subset", "class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a", "is None: raise ValueError(\"D3PO Export restricted to 0 or 1", "bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler", "subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i)", "= {} def save_page(page, page_number, label, subset): \"\"\" Convert a", "already taken pass print('Serving D3PO on port 0.0.0.0:%i' % PORT)", "return tuple(result) def can_save_d3po(application): \"\"\" Check whether an application can", "<script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script", "# show the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start", "save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)])", "selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected", "\"and histogram plots\") if sum(len(tab) for tab in application.viewers) ==", "given Data and tuple of subsets \"\"\" from astropy.table import", "Raises an exception if not \"\"\" dc = application.session.data_collection if", "d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color)", "of subsets \"\"\" from astropy.table import Table, Column data_path =", "= selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number}", "a single histogram to a D3PO plot :param plot: Glue", "# do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def", "page :param page: Tuple of data viewers to save :param", "subset = s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check", "from glue.core import Subset DISPATCH = {} def save_page(page, page_number,", "import json from glue.core import Subset DISPATCH = {} def", "if subset is not None: s = subset.style selected =", "as outfile: outfile.write(HTML) # show the result if launch: launch_d3po(path)", "= TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break", "if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if", "{ position: fixed; bottom: 0; right: 0; } </style> <!--", "len(page)} result['name'] = str(label) result['caption'] = 'Generated by Glue' #", "to a D3PO bundle. Currently, this has the following restrictions:", "os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets =", "href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom: 0;", "delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue session to", "</body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt", "application can be exported to D3PO. Raises an exception if", "- At least one plot is present :param application: Glue", "application.viewers # data.csv make_data_file(data, subsets, path) # states.json result =", "save_scatter(plot, index): \"\"\" Convert a single glue scatter plot to", "plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the", "return result def save_histogram(plot, index): \"\"\" Convert a single histogram", "only supports scatter \" \"and histogram plots\") if sum(len(tab) for", "} </style> <!-- not to be confused with Planet Telex", "2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn', 'columnName':", "os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets", "1 subsets - Only scatter plots or histograms are present", "<div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script", "<ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information:", "raise ValueError(\"D3PO Export requires at least one scatterplot \" \"or", "must have only one dataset open, and 0 or 1", "% PORT) def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po,", "dataset open, and 0 or 1 subsets - Only scatter", "single glue scatter plot to a D3PO plot :param plot:", "\"\"\" Check whether an application can be exported to D3PO.", "raise ValueError(\"D3PO Export only supports a single dataset\") for tab", "type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a", ":param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index", "open a browser. :param path: The TLD of the bundle", "import error import webbrowser from threading import Thread os.chdir(path) while", "histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted to", "directory to save in. Will be created if needed \"\"\"", "= os.path.join(path, 'data.csv') t = Table([data[c] for c in data.components],", "each stage/tab, or None if the tab has no subset", "stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets, path) #", "= \"Glue export of %s\" % data.label result['states'] = list(map(save_page,", "'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save", "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700'", "than one subset is used per stage/tab, returns None \"\"\"", "\"\"\" Convert a tab of a glue session into a", "Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot", "None for viewer in page: for layer_artist in viewer.layers: if", "import randrange from socket import error import webbrowser from threading", "</html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import", "D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever)", "'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save each", "socket import error import webbrowser from threading import Thread os.chdir(path)", "continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii',", "to save :param path: Path to directory to save in.", "\"\"\" Return a tuple of the subset to use for", "save_page(page, page_number, label, subset): \"\"\" Convert a tab of a", "= Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i'", "<!-- not to be confused with Planet Telex --> <!--", "plot is present :param application: Glue appication to save :param", "page_number, label, subset): \"\"\" Convert a tab of a glue", "!= 1: raise ValueError(\"D3PO Export only supports a single dataset\")", "to save :param label: Tab label \"\"\" result = {}", "os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers =", ":param index: 1D index of plot on the page :type", "c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',')", "scales return result def save_histogram(plot, index): \"\"\" Convert a single", "= dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log", "color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not None: s", "if len(dc) != 1: raise ValueError(\"D3PO Export only supports a", "is needed? result['title'] = \"Glue export of %s\" % data.label", "application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path,", "index): \"\"\" Convert a single histogram to a D3PO plot", "normed, cumultive, log return result def stage_subsets(application): \"\"\" Return a", "name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path,", "# index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as", "position: fixed; bottom: 0; right: 0; } </style> <!-- not", "not os.path.isdir(path): os.unlink(path) if not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0]", "be exported to D3PO. Raises an exception if not \"\"\"", ":param application: Glue appication to save :param path: Path to", "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer", "D3PO page :param page: Tuple of data viewers to save", "PORT) def setup(): from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po,", "path) # states.json result = {} result['filename'] = 'data.csv' #", "'data.csv') t = Table([data[c] for c in data.components], names=[c.label for", ":type index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot,", "can_save_d3po(application): \"\"\" Check whether an application can be exported to", "while True: try: PORT = randrange(8000, 9000) server = TCPServer((\"\",", "for i, subset in enumerate(subsets): if subset is None: continue", "{'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated", "the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import", "__future__ import absolute_import, division, print_function import os import json from", "think this is needed? result['title'] = \"Glue export of %s\"", "requires at least one scatterplot \" \"or histogram\") if stage_subsets(application)", "page: for layer_artist in viewer.layers: if not layer_artist.visible: continue s", "application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data,", "def save_page(page, page_number, label, subset): \"\"\" Convert a tab of", "Will be created if needed \"\"\" if os.path.exists(path) and not", "webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import exporters exporters.add('D3PO',", "result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return", "result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether an application", "json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram'", "{} # layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)}", "layer_artist.visible: continue s = layer_artist.layer if not isinstance(s, Subset): continue", "outfile.write(HTML) # show the result if launch: launch_d3po(path) def launch_d3po(path):", "data viewers to save :param label: Tab label \"\"\" result", "sum(len(tab) for tab in application.viewers) == 0: raise ValueError(\"D3PO Export", "1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated by", "with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) #", "type='text/css'> <style> #footer { position: fixed; bottom: 0; right: 0;", "is not None and s is not subset: return None", "Check whether an application can be exported to D3PO. Raises", "result['filename'] = 'data.csv' # XXX don't think this is needed?", "index.html html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as outfile:", "result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] =", "subset is None: subset = s result.append(subset) return tuple(result) def", "in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only", "exported to D3PO. Raises an exception if not \"\"\" dc", "rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet'", "<script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body>", "# layout settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name']", "dataset\") for tab in application.viewers: for viewer in tab: if", "Glue appication to save :param path: Path to directory to", "\"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] =", "the page :type index: int :rtype: json-serializable dict \"\"\" result", "view an exported D3PO bundle, and open a browser. :param", "import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError: pass else:", "make_data_file(data, subsets, path) # states.json result = {} result['filename'] =", "def can_save_d3po(application): \"\"\" Check whether an application can be exported", "confused with Planet Telex --> <!-- Javscript dependencies --> <script", "needed? result['title'] = \"Glue export of %s\" % data.label result['states']", "= os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile,", "Currently, this has the following restrictions: - The Glue session", "histograms are present - At least one plot is present", "result = [] for page in application.viewers: subset = None", "glue.core import Subset DISPATCH = {} def save_page(page, page_number, label,", "label \"\"\" result = {} # layout settings result['grid'] =", "of a glue session into a D3PO page :param page:", "t = Table([data[c] for c in data.components], names=[c.label for c", "t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a", "= application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers # data.csv", "thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start()", "result['plots'] = list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index):", "outfile: outfile.write(HTML) # show the result if launch: launch_d3po(path) def", "print('Serving D3PO on port 0.0.0.0:%i' % PORT) server.server_activate() thread =", "from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random", "not None and s is not subset: return None if", "<style> #footer { position: fixed; bottom: 0; right: 0; }", ":param label: Tab label \"\"\" result = {} # layout", "return result def save_plot_base(plot, index): result = {} result['gridPosition'] =", "html_path = os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML)", "whether an application can be exported to D3PO. Raises an", "def make_data_file(data, subsets, path): \"\"\" Create the data.csv file, given", "</script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from", "Export only supports scatter \" \"and histogram plots\") if sum(len(tab)", "XXX don't think this is needed? result['title'] = \"Glue export", "DISPATCH = {} def save_page(page, page_number, label, subset): \"\"\" Convert", "PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except error:", "Convert a single glue scatter plot to a D3PO plot", "Subset): continue if subset is not None and s is", "not \"\"\" dc = application.session.data_collection if len(dc) != 1: raise", "this is needed? result['title'] = \"Glue export of %s\" %", "Thread os.chdir(path) while True: try: PORT = randrange(8000, 9000) server", "Path to directory to save in. Will be created if", "glue scatter plot to a D3PO plot :param plot: Glue", "plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index:", "import absolute_import, division, print_function import os import json from glue.core", "into a D3PO page :param page: Tuple of data viewers", "subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] =", "and tuple of subsets \"\"\" from astropy.table import Table, Column", "\" \"in each tab\") def make_data_file(data, subsets, path): \"\"\" Create", ":class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of plot on the page", "if subset is not None and s is not subset:", "not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from", "dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] =", "def stage_subsets(application): \"\"\" Return a tuple of the subset to", "states.json result = {} result['filename'] = 'data.csv' # XXX don't", "i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save", "of %s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names,", "style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize /", "'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True)", "per stage/tab, returns None \"\"\" result = [] for page", "or 1 subsets - Only scatter plots or histograms are", "def launch_d3po(path): \"\"\"Start a server to view an exported D3PO", "except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter DISPATCH[HistogramViewer] = save_histogram", "make_data_file(data, subsets, path): \"\"\" Create the data.csv file, given Data", "index of plot on the page :type index: int :rtype:", "to be confused with Planet Telex --> <!-- Javscript dependencies", "Convert a tab of a glue session into a D3PO", "visible \" \"in each tab\") def make_data_file(data, subsets, path): \"\"\"", "False) server.allow_reuse_address = True server.server_bind() break except error: # port", "randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address =", "os.path.join(path, 'data.csv') t = Table([data[c] for c in data.components], names=[c.label", "tab of a glue session into a D3PO page :param", "{ initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\" try:", "in page: for layer_artist in viewer.layers: if not layer_artist.visible: continue", "def save_d3po(application, path, launch=True): \"\"\"Save a Glue session to a", "a tuple of the subset to use for each stage/tab,", "to D3PO. Raises an exception if not \"\"\" dc =", "0: raise ValueError(\"D3PO Export requires at least one scatterplot \"", "= dict(unselected=unselected) if subset is not None: s = subset.style", "import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange", "unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected)", "1: raise ValueError(\"D3PO Export only supports a single dataset\") for", "src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div", "scatterplot \" \"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO", "id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More", "\"or histogram\") if stage_subsets(application) is None: raise ValueError(\"D3PO Export restricted", "\"\"\" result = [] for page in application.viewers: subset =", "port already taken pass print('Serving D3PO on port 0.0.0.0:%i' %", "page in application.viewers: subset = None for viewer in page:", "if not isinstance(s, Subset): continue if subset is not None", "None if subset is None: subset = s result.append(subset) return", "Create the data.csv file, given Data and tuple of subsets", "D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index:", "Thread(target=server.serve_forever) thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' %", "XXX normed, cumultive, log return result def stage_subsets(application): \"\"\" Return", "src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script>", "result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to", "'nColumns': len(page)} result['name'] = str(label) result['caption'] = 'Generated by Glue'", "a D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param", "and s is not subset: return None if subset is", "an exception if not \"\"\" dc = application.session.data_collection if len(dc)", "str(label) result['caption'] = 'Generated by Glue' # style settings d", "\"Glue export of %s\" % data.label result['states'] = list(map(save_page, application.viewers,", "None \"\"\" result = [] for page in application.viewers: subset", "result['histogramStyle'] = result['markerStyle'] # save each plot result['plots'] = list(map(save_plot,", "the subset to use for each stage/tab, or None if", "for page in application.viewers: subset = None for viewer in", "Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script", "path: The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import", "</style> <!-- not to be confused with Planet Telex -->", "'Generated by Glue' # style settings d = page[0]._data[0] unselected", "division, print_function import os import json from glue.core import Subset", "as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path =", "tab in application.viewers) == 0: raise ValueError(\"D3PO Export requires at", "dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis']", "{'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] #", "result['caption'] = 'Generated by Glue' # style settings d =", "len(dc) != 1: raise ValueError(\"D3PO Export only supports a single", "Glue session must have only one dataset open, and 0", "single histogram to a D3PO plot :param plot: Glue histogram", "# XXX normed, cumultive, log return result def stage_subsets(application): \"\"\"", "present :param application: Glue appication to save :param path: Path", "from socket import error import webbrowser from threading import Thread", "plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot,", "index): \"\"\" Convert a single glue scatter plot to a", "= Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c) t.write(data_path, format='ascii', delimiter=',') def", "0 or 1 subsets visible \" \"in each tab\") def", "or None if the tab has no subset If more", "path): \"\"\" Create the data.csv file, given Data and tuple", "float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result def stage_subsets(application):", "bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return result", "type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position:", "file, given Data and tuple of subsets \"\"\" from astropy.table", "label, subset): \"\"\" Convert a tab of a glue session", "glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\"", "range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result def save_histogram(plot,", "result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) #", "= None for viewer in page: for layer_artist in viewer.layers:", "a single dataset\") for tab in application.viewers: for viewer in", "= {} # layout settings result['grid'] = {'nRows': 1, 'nColumns':", "- The Glue session must have only one dataset open,", "subsets visible \" \"in each tab\") def make_data_file(data, subsets, path):", "SimpleHTTPRequestHandler from random import randrange from socket import error import", "show the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a", "can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta", "in application.viewers) == 0: raise ValueError(\"D3PO Export requires at least", "single dataset\") for tab in application.viewers: for viewer in tab:", "not None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize /", "data_path = os.path.join(path, 'data.csv') t = Table([data[c] for c in", "\"\"\" result = {} # layout settings result['grid'] = {'nRows':", "subsets = stage_subsets(application) viewers = application.viewers # data.csv make_data_file(data, subsets,", "= \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link", "only one dataset open, and 0 or 1 subsets -", "= dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if", "in enumerate(subsets): if subset is None: continue c = Column(data=subset.to_mask().astype('i'),", "enumerate(subsets): if subset is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i'", "src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul", "for each stage/tab, or None if the tab has no", "import HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter DISPATCH[HistogramViewer]", "this has the following restrictions: - The Glue session must", "supports a single dataset\") for tab in application.viewers: for viewer", ":param page: Tuple of data viewers to save :param label:", "tab\") def make_data_file(data, subsets, path): \"\"\" Create the data.csv file,", "= layer_artist.layer if not isinstance(s, Subset): continue if subset is", "= os.path.join(path, 'index.html') with open(html_path, 'w') as outfile: outfile.write(HTML) #", "webbrowser from threading import Thread os.chdir(path) while True: try: PORT", "\"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\"", "'selection_%i' % page_number} result['histogramStyle'] = result['markerStyle'] # save each plot", "= list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index): result", "save_histogram(plot, index): \"\"\" Convert a single histogram to a D3PO", "appication to save :param path: Path to directory to save", "href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } );", "exception if not \"\"\" dc = application.session.data_collection if len(dc) !=", "result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label,", "tab in application.viewers: for viewer in tab: if not isinstance(viewer,", "least one plot is present :param application: Glue appication to", "is None: continue c = Column(data=subset.to_mask().astype('i'), name='selection_%i' % i) t.add_column(c)", "glue session into a D3PO page :param page: Tuple of", "continue s = layer_artist.layer if not isinstance(s, Subset): continue if", "bundle, and open a browser. :param path: The TLD of", "return None if subset is None: subset = s result.append(subset)", "is present :param application: Glue appication to save :param path:", "in viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer if", "a D3PO bundle. Currently, this has the following restrictions: -", "src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul>", "for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO", "# save each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return", "'data.csv' # XXX don't think this is needed? result['title'] =", "page_number} result['histogramStyle'] = result['markerStyle'] # save each plot result['plots'] =", "absolute_import, division, print_function import os import json from glue.core import", "or histograms are present - At least one plot is", "thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import exporters", "'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min),", "= save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin),", "one subset is used per stage/tab, returns None \"\"\" result", "result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle'] =", "viewer in page: for layer_artist in viewer.layers: if not layer_artist.visible:", "a D3PO page :param page: Tuple of data viewers to", "to a D3PO plot :param plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer`", "= type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert", "float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales", "tuple of the subset to use for each stage/tab, or", "os.path.join(path, 'states.json') with open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2,", "result = {} result['gridPosition'] = [0, index] return result def", "'w') as outfile: outfile.write(HTML) # show the result if launch:", "have only one dataset open, and 0 or 1 subsets", "SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except error: #", "server.server_bind() break except error: # port already taken pass print('Serving", "<a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); }", "not to be confused with Planet Telex --> <!-- Javscript", "dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'histogram' result['xAxis']", "s = layer_artist.layer if not isinstance(s, Subset): continue if subset", "<div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div id=\"caption\"></div>", "None: raise ValueError(\"D3PO Export restricted to 0 or 1 subsets", "[0, index] return result def save_plot(plot, index): typ = type(plot)", "subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as outfile:", "os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers", "to 0 or 1 subsets visible \" \"in each tab\")", "s result.append(subset) return tuple(result) def can_save_d3po(application): \"\"\" Check whether an", "on port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True)", "subset is not None: s = subset.style selected = dict(opacity=s.alpha,", "application.viewers: subset = None for viewer in page: for layer_artist", "= [0, index] return result def save_plot(plot, index): typ =", "% PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do not", "application.viewers: for viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise", "Table([data[c] for c in data.components], names=[c.label for c in data.components])", "</div> <script type=\"text/javascript\"> $(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script>", "from __future__ import absolute_import, division, print_function import os import json", "return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a single", "supports scatter \" \"and histogram plots\") if sum(len(tab) for tab", "charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\">", "outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path,", "Tuple of data viewers to save :param label: Tab label", "index] return result def save_plot(plot, index): typ = type(plot) return", "#footer { position: fixed; bottom: 0; right: 0; } </style>", "0 or 1 subsets - Only scatter plots or histograms", "Only scatter plots or histograms are present - At least", "True server.server_bind() break except error: # port already taken pass", "/> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link", "0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) # do", "json-serializable dict \"\"\" result = save_plot_base(plot, index) result['type'] = 'scatter'", "viewers = application.viewers # data.csv make_data_file(data, subsets, path) # states.json", "outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"", "export of %s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)),", "2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is not None:", "if not layer_artist.visible: continue s = layer_artist.layer if not isinstance(s,", "= [] for page in application.viewers: subset = None for", "page: Tuple of data viewers to save :param label: Tab", "Tab label \"\"\" result = {} # layout settings result['grid']", "Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script>", "for tab in application.viewers: for viewer in tab: if not", "dc = application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export", "prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config", "an exported D3PO bundle, and open a browser. :param path:", "label: Tab label \"\"\" result = {} # layout settings", "save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html> <html> <head>", "- Only scatter plots or histograms are present - At", "plot: Glue scatter plot :class:`~glue.viewers.scatter.qt.ScatterViewer` :param index: 1D index of", "list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with", "each tab\") def make_data_file(data, subsets, path): \"\"\" Create the data.csv", "<body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\"> </ul> </div> <div", "= 'Generated by Glue' # style settings d = page[0]._data[0]", "plot to a D3PO plot :param plot: Glue scatter plot", "from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from random import randrange from socket", "histogram to a D3PO plot :param plot: Glue histogram :type", "if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view", "browser. :param path: The TLD of the bundle \"\"\" from", "result def save_histogram(plot, index): \"\"\" Convert a single histogram to", "session to a D3PO bundle. Currently, this has the following", "import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE", "log return result def stage_subsets(application): \"\"\" Return a tuple of", "a Glue session to a D3PO bundle. Currently, this has", "application.viewers) == 0: raise ValueError(\"D3PO Export requires at least one", "needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path) if not", "9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True", "\"\"\"Start a server to view an exported D3PO bundle, and", "on the page :type index: int :rtype: json-serializable dict \"\"\"", "'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed,", "= Table([data[c] for c in data.components], names=[c.label for c in", "result = save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label,", "subset in enumerate(subsets): if subset is None: continue c =", "server to view an exported D3PO bundle, and open a", "ValueError(\"D3PO Export only supports scatter \" \"and histogram plots\") if", "print_function import os import json from glue.core import Subset DISPATCH", "--> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script>", "$(document).ready(function() { initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\"", "{} result['gridPosition'] = [0, index] return result def save_plot(plot, index):", "are present - At least one plot is present :param", "</ul> </div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a>", "don't think this is needed? result['title'] = \"Glue export of", "server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind()", "} ); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import", "dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result def", "a single glue scatter plot to a D3PO plot :param", "= list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path, 'states.json')", "c in data.components]) for i, subset in enumerate(subsets): if subset", "application.session.data_collection if len(dc) != 1: raise ValueError(\"D3PO Export only supports", "at least one scatterplot \" \"or histogram\") if stage_subsets(application) is", "viewers to save :param label: Tab label \"\"\" result =", "stage_subsets(application): \"\"\" Return a tuple of the subset to use", "[] for page in application.viewers: subset = None for viewer", "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\"", "subset = None for viewer in page: for layer_artist in", "src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div", "id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function() {", "data = application.session.data_collection[0] subsets = stage_subsets(application) viewers = application.viewers #", "result['gridPosition'] = [0, index] return result def save_plot(plot, index): typ", "for layer_artist in viewer.layers: if not layer_artist.visible: continue s =", "a D3PO plot :param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer`", "random import randrange from socket import error import webbrowser from", "plots\") if sum(len(tab) for tab in application.viewers) == 0: raise", "open(state_path, 'w') as outfile: json.dump(result, outfile, indent=2, sort_keys=True) # index.html", "exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML = \"\"\" <!DOCTYPE html>", "index) def save_scatter(plot, index): \"\"\" Convert a single glue scatter", "index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis']", "least one scatterplot \" \"or histogram\") if stage_subsets(application) is None:", "format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue session", "with open(html_path, 'w') as outfile: outfile.write(HTML) # show the result", "and 0 or 1 subsets - Only scatter plots or", "= dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)]) # XXX log scales return result", "shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup(): from glue.config import", "PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False)", "scatter plot to a D3PO plot :param plot: Glue scatter", "created if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path): os.unlink(path)", "\"\"\" try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer", "error: # port already taken pass print('Serving D3PO on port", "subsets, path) # states.json result = {} result['filename'] = 'data.csv'", "if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter", "Glue session to a D3PO bundle. Currently, this has the", "); </script> </body> </html> \"\"\" try: from glue.viewers.scatter.qt import ScatterViewer", "tab has no subset If more than one subset is", "a glue session into a D3PO page :param page: Tuple", "TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address = True server.server_bind() break except", "outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html') with", "from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except ImportError:", "not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \"", "ValueError(\"D3PO Export only supports a single dataset\") for tab in", "1D index of plot on the page :type index: int", "result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min), float(plot.state.x_max)]) result['yAxis'] = dict(columnName=plot.state.y_att.label, range=[float(plot.state.y_min), float(plot.state.y_max)])", "= application.viewers # data.csv make_data_file(data, subsets, path) # states.json result", "t.write(data_path, format='ascii', delimiter=',') def save_d3po(application, path, launch=True): \"\"\"Save a Glue", "The TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer", "def save_plot_base(plot, index): result = {} result['gridPosition'] = [0, index]", "i, subset in enumerate(subsets): if subset is None: continue c", "<div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div> <script type=\"text/javascript\"> $(document).ready(function()", "rel='stylesheet' type='text/css'> <style> #footer { position: fixed; bottom: 0; right:", "raise ValueError(\"D3PO Export only supports scatter \" \"and histogram plots\")", "application: Glue appication to save :param path: Path to directory", "= save_plot_base(plot, index) result['type'] = 'scatter' result['xAxis'] = dict(columnName=plot.state.x_att.label, range=[float(plot.state.x_min),", "stage/tab, or None if the tab has no subset If", "scatter \" \"and histogram plots\") if sum(len(tab) for tab in", "do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT) def setup():", "right: 0; } </style> <!-- not to be confused with", ":param plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D", "</div> <div id=\"caption\"></div> <div id=\"footer\"> More information: <a href=\"http://d3po.org\">d3po.org</a> </div>", "result['markerStyle'] = dict(unselected=unselected) if subset is not None: s =", "if not \"\"\" dc = application.session.data_collection if len(dc) != 1:", "result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption']", "plot on the page :type index: int :rtype: json-serializable dict", "one scatterplot \" \"or histogram\") if stage_subsets(application) is None: raise", "1 subsets visible \" \"in each tab\") def make_data_file(data, subsets,", "the tab has no subset If more than one subset", "<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script src=\"http://d3po.org/static/js/d3po.js\"></script> <script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div>", "use for each stage/tab, or None if the tab has", "subset If more than one subset is used per stage/tab,", "%s\" % data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets))", "is used per stage/tab, returns None \"\"\" result = []", "True: try: PORT = randrange(8000, 9000) server = TCPServer((\"\", PORT),", "page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] =", "selected result['selection'] = {'type': 'booleanColumn', 'columnName': 'selection_%i' % page_number} result['histogramStyle']", "to use for each stage/tab, or None if the tab", "layer_artist in viewer.layers: if not layer_artist.visible: continue s = layer_artist.layer", "href=\"http://d3po.org/static/css/style.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style>", "Data and tuple of subsets \"\"\" from astropy.table import Table,", "size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset is", "ValueError(\"D3PO Export restricted to 0 or 1 subsets visible \"", "subsets - Only scatter plots or histograms are present -", "port 0.0.0.0:%i' % PORT) server.server_activate() thread = Thread(target=server.serve_forever) thread.setDaemon(True) #", "tuple(result) def can_save_d3po(application): \"\"\" Check whether an application can be", "index: int :rtype: json-serializable dict \"\"\" result = save_plot_base(plot, index)", "0; } </style> <!-- not to be confused with Planet", "\"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer import SimpleHTTPRequestHandler from", "json.dump(result, outfile, indent=2, sort_keys=True) # index.html html_path = os.path.join(path, 'index.html')", "Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index of", "= {} result['filename'] = 'data.csv' # XXX don't think this", "save :param path: Path to directory to save in. Will", "log scales return result def save_histogram(plot, index): \"\"\" Convert a", "session into a D3PO page :param page: Tuple of data", "path, launch=True): \"\"\"Save a Glue session to a D3PO bundle.", "a tab of a glue session into a D3PO page", "of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from glue.external.six.moves.SimpleHTTPServer", "range(len(page)))) return result def save_plot_base(plot, index): result = {} result['gridPosition']", "c in data.components], names=[c.label for c in data.components]) for i,", "not layer_artist.visible: continue s = layer_artist.layer if not isinstance(s, Subset):", "# XXX don't think this is needed? result['title'] = \"Glue", "except error: # port already taken pass print('Serving D3PO on", "the following restrictions: - The Glue session must have only", "viewer in tab: if not isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export", "break except error: # port already taken pass print('Serving D3PO", "bottom: 0; right: 0; } </style> <!-- not to be", "restricted to 0 or 1 subsets visible \" \"in each", "following restrictions: - The Glue session must have only one", "result['name'] = str(label) result['caption'] = 'Generated by Glue' # style", "by Glue' # style settings d = page[0]._data[0] unselected =", "subsets, path): \"\"\" Create the data.csv file, given Data and", "s = subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2, color=s.color)", "save_plot_base(plot, index): result = {} result['gridPosition'] = [0, index] return", "save in. Will be created if needed \"\"\" if os.path.exists(path)", "result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path = os.path.join(path,", "TLD of the bundle \"\"\" from glue.external.six.moves.socketserver import TCPServer from", "= {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label) result['caption'] =", "list(map(save_plot, page, range(len(page)))) return result def save_plot_base(plot, index): result =", "D3PO bundle, and open a browser. :param path: The TLD", "DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\" Convert a single glue", "is not subset: return None if subset is None: subset", "ValueError(\"D3PO Export requires at least one scatterplot \" \"or histogram\")", "isinstance(viewer, tuple(DISPATCH.keys())): raise ValueError(\"D3PO Export only supports scatter \" \"and", "At least one plot is present :param application: Glue appication", "dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\" charset=\"utf-8\"></script> <script src=\"http://d3po.org/static/js/util.js\"></script> <script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script> <script", "typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index): \"\"\"", "Subset DISPATCH = {} def save_page(page, page_number, label, subset): \"\"\"", "<html> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"http://d3po.org/static/css/style.css\"> <link", "launch_d3po(path): \"\"\"Start a server to view an exported D3PO bundle,", "and open a browser. :param path: The TLD of the", "if the tab has no subset If more than one", "s is not subset: return None if subset is None:", "be created if needed \"\"\" if os.path.exists(path) and not os.path.isdir(path):", "= randrange(8000, 9000) server = TCPServer((\"\", PORT), SimpleHTTPRequestHandler, False) server.allow_reuse_address", "href=\"http://d3po.org/static/css/d3po.css\"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400,700' rel='stylesheet' type='text/css'> <style> #footer { position: fixed;", "def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot, index) def", "the result if launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server", "only supports a single dataset\") for tab in application.viewers: for", "cumultive, log return result def stage_subsets(application): \"\"\" Return a tuple", "one dataset open, and 0 or 1 subsets - Only", "plot: Glue histogram :type plot: :class:`~glue.viewers.histogram.qt.HistogramViewer` :param index: 1D index", "The Glue session must have only one dataset open, and", "# style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize", "index): typ = type(plot) return DISPATCH[typ](plot, index) def save_scatter(plot, index):", "application.tab_names, subsets)) state_path = os.path.join(path, 'states.json') with open(state_path, 'w') as", "= dict(opacity=s.alpha, size=s.markersize / 2, color=s.color) result['markerStyle']['selected'] = selected result['selection']", "present - At least one plot is present :param application:", "= 'histogram' result['xAxis'] = dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX", "== 0: raise ValueError(\"D3PO Export requires at least one scatterplot", "page :type index: int :rtype: json-serializable dict \"\"\" result =", "Glue' # style settings d = page[0]._data[0] unselected = dict(opacity=d.style.alpha,", "subset to use for each stage/tab, or None if the", "HistogramViewer except ImportError: pass else: DISPATCH[ScatterViewer] = save_scatter DISPATCH[HistogramViewer] =", "{} result['filename'] = 'data.csv' # XXX don't think this is", "with Planet Telex --> <!-- Javscript dependencies --> <script src=\"http://d3js.org/d3.v3.min.js\"", "not os.path.exists(path): os.mkdir(path) data = application.session.data_collection[0] subsets = stage_subsets(application) viewers", "result['title'] = \"Glue export of %s\" % data.label result['states'] =", "= 'data.csv' # XXX don't think this is needed? result['title']", "isinstance(s, Subset): continue if subset is not None and s", "thread.setDaemon(True) # do not prevent shutdown thread.start() webbrowser.open('http://0.0.0.0:%i' % PORT)", "continue if subset is not None and s is not", "save each plot result['plots'] = list(map(save_plot, page, range(len(page)))) return result", "= page[0]._data[0] unselected = dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle']", "initialize('states.json', 'data.csv'); } ); </script> </body> </html> \"\"\" try: from", "# states.json result = {} result['filename'] = 'data.csv' # XXX", "data.label result['states'] = list(map(save_page, application.viewers, range(len(viewers)), application.tab_names, subsets)) state_path =", "subsets \"\"\" from astropy.table import Table, Column data_path = os.path.join(path,", "for c in data.components], names=[c.label for c in data.components]) for", "threading import Thread os.chdir(path) while True: try: PORT = randrange(8000,", "D3PO bundle. Currently, this has the following restrictions: - The", "None: s = subset.style selected = dict(opacity=s.alpha, size=s.markersize / 2,", "dict(columnName=plot.state.x_att.label, bins=int(plot.state.hist_n_bin), range=[float(plot.state.hist_x_min), float(plot.state.hist_x_max)]) # XXX normed, cumultive, log return", "return result def save_plot(plot, index): typ = type(plot) return DISPATCH[typ](plot,", "# XXX log scales return result def save_histogram(plot, index): \"\"\"", "launch: launch_d3po(path) def launch_d3po(path): \"\"\"Start a server to view an", "dict(opacity=d.style.alpha, size=d.style.markersize / 2, color=d.style.color) result['markerStyle'] = dict(unselected=unselected) if subset", "/ 2, color=s.color) result['markerStyle']['selected'] = selected result['selection'] = {'type': 'booleanColumn',", "XXX log scales return result def save_histogram(plot, index): \"\"\" Convert", "path: Path to directory to save in. Will be created", "# port already taken pass print('Serving D3PO on port 0.0.0.0:%i'", "more than one subset is used per stage/tab, returns None", "<script src=\"http://d3po.org/static/js/d3po.init.js\"></script> </head> <body> <div id=\"svg\"><svg></svg></div> <div id=\"controls\"> <ul class=\"navigation\">", "from glue.config import exporters exporters.add('D3PO', save_d3po, can_save_d3po, outmode='directory') HTML =", "settings result['grid'] = {'nRows': 1, 'nColumns': len(page)} result['name'] = str(label)", "try: from glue.viewers.scatter.qt import ScatterViewer from glue.viewers.histogram.qt import HistogramViewer except", "0; right: 0; } </style> <!-- not to be confused", "to a D3PO plot :param plot: Glue histogram :type plot:", "stage/tab, returns None \"\"\" result = [] for page in" ]
[ "a razão: ')) termo = n1 c = 1 print('A", "é (', end='') while c <= 10: print('{}'.format(termo), end='') print(',", "end='') while c <= 10: print('{}'.format(termo), end='') print(', ' if", "')) termo = n1 c = 1 print('A P.A. é", "print('{}'.format(termo), end='') print(', ' if c < 10 else '',", "10 else '', end='') termo += r c += 1", "o primeiro termo da P.A.: ')) r = int(input('Digite a", "c = 1 print('A P.A. é (', end='') while c", "print('A P.A. é (', end='') while c <= 10: print('{}'.format(termo),", "r = int(input('Digite a razão: ')) termo = n1 c", "else '', end='') termo += r c += 1 print(')')", "de 10 termos') n1 = int(input('Digite o primeiro termo da", "P.A. é (', end='') while c <= 10: print('{}'.format(termo), end='')", "<gh_stars>0 print('Crie sua P.A. de 10 termos') n1 = int(input('Digite", "')) r = int(input('Digite a razão: ')) termo = n1", "if c < 10 else '', end='') termo += r", "int(input('Digite a razão: ')) termo = n1 c = 1", "= int(input('Digite a razão: ')) termo = n1 c =", "1 print('A P.A. é (', end='') while c <= 10:", "10: print('{}'.format(termo), end='') print(', ' if c < 10 else", "= 1 print('A P.A. é (', end='') while c <=", "n1 c = 1 print('A P.A. é (', end='') while", "sua P.A. de 10 termos') n1 = int(input('Digite o primeiro", "print('Crie sua P.A. de 10 termos') n1 = int(input('Digite o", "P.A.: ')) r = int(input('Digite a razão: ')) termo =", "= int(input('Digite o primeiro termo da P.A.: ')) r =", "razão: ')) termo = n1 c = 1 print('A P.A.", "termo = n1 c = 1 print('A P.A. é (',", "< 10 else '', end='') termo += r c +=", "10 termos') n1 = int(input('Digite o primeiro termo da P.A.:", "P.A. de 10 termos') n1 = int(input('Digite o primeiro termo", "int(input('Digite o primeiro termo da P.A.: ')) r = int(input('Digite", "(', end='') while c <= 10: print('{}'.format(termo), end='') print(', '", "end='') print(', ' if c < 10 else '', end='')", "da P.A.: ')) r = int(input('Digite a razão: ')) termo", "print(', ' if c < 10 else '', end='') termo", "c <= 10: print('{}'.format(termo), end='') print(', ' if c <", "primeiro termo da P.A.: ')) r = int(input('Digite a razão:", "= n1 c = 1 print('A P.A. é (', end='')", "termo da P.A.: ')) r = int(input('Digite a razão: '))", "<= 10: print('{}'.format(termo), end='') print(', ' if c < 10", "c < 10 else '', end='') termo += r c", "while c <= 10: print('{}'.format(termo), end='') print(', ' if c", "n1 = int(input('Digite o primeiro termo da P.A.: ')) r", "' if c < 10 else '', end='') termo +=", "termos') n1 = int(input('Digite o primeiro termo da P.A.: '))" ]
[ "= location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body,", "provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a", "is called). The connection will be unusable from this point", "host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = []", "first will cause an implicit rollback to be performed.\"\"\" self._connection.close()", "':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection =", "The same applies to all cursor objects trying to use", "+= 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s", "ImportError: # pylint: disable=import-error from urlparse import urlparse from .constants", "from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, )", "self.messages = [] self.scheme = scheme self.host = host self.port", "'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' %", "ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>,", "self.close() def commit(self): \"\"\"Database modules that do not support transactions", "from this point forward; an Error (or subclass) exception will", "or password is None): self._headers['Authorization'] = 'Basic ' + \\", "_EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions", "exception will be raised if any operation is attempted with", "self.host = location.hostname self.port = location.port self._connection = self._init_connection() response", "PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error,", "self.scheme = scheme self.host = host self.port = port self._headers", "factory(self) else: return Cursor(self) def execute(self, *args, **kwargs): return self.cursor().execute(*args,", "self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme ==", "import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError:", "self.host = host self.port = port self._headers = {} if", "commit(self): \"\"\"Database modules that do not support transactions should implement", "headers={}): \"\"\" Fetch a response, handling redirection. \"\"\" response =", "rollback(self): \"\"\"This method is optional since not all databases provide", "self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else", "_fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a response, handling", "with the connection. The same applies to all cursor objects", "urlparse except ImportError: # pylint: disable=import-error from urlparse import urlparse", "\"\"\"Return a new Cursor Object using the connection.\"\"\" if factory:", "cursor objects trying to use the connection. Note that closing", "self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http',", "Cursor Object using the connection.\"\"\" if factory: return factory(self) else:", "as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from", "connection. Note that closing a connection without committing the changes", "a new Cursor Object using the connection.\"\"\" if factory: return", "= [] self.scheme = scheme self.host = host self.port =", "the changes first will cause an implicit rollback to be", "max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames", "= 0 while response.status == 301 and \\ response.getheader('Location') is", "if factory: return factory(self) else: return Cursor(self) def execute(self, *args,", "Exception: if not tries: raise self._connection.close() self._connection = self._init_connection() def", "= self._retry_request(method, uri, body=body, headers=headers) return response def close(self): \"\"\"Close", "= _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def", ".cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from", "= connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes =", "Note that closing a connection without committing the changes first", "None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n')", "from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError,", "self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a", "'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types", "method, uri, body=None, headers={}): tries = 10 while tries: tries", "return factory(self) else: return Cursor(self) def execute(self, *args, **kwargs): return", "else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries =", "from __future__ import unicode_literals import codecs import logging try: from", "__future__ import unicode_literals import codecs import logging try: from http.client", "user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme =", "\"\"\" pass def cursor(self, factory=None): \"\"\"Return a new Cursor Object", "import urlparse except ImportError: # pylint: disable=import-error from urlparse import", "from urllib.parse import urlparse except ImportError: # pylint: disable=import-error from", "raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None,", "= None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host,", "self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection()", "a response, handling redirection. \"\"\" response = self._retry_request(method, uri, body=body,", "timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method,", "if any operation is attempted with the connection. The same", "that closing a connection without committing the changes first will", "10 while tries: tries -= 1 try: self._connection.request(method, uri, body=body,", "\\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects", "disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import", "except ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection", "factory: return factory(self) else: return Cursor(self) def execute(self, *args, **kwargs):", "self._headers = {} if not (user is None or password", "reason: '%s' location: '%s'\", response.status, response.reason, uri) if self.host !=", "location.hostname self.port = location.port self._connection = self._init_connection() response = self._retry_request(method,", "headers=headers) return response def close(self): \"\"\"Close the connection now (rather", "HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except ImportError: #", ".extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import (", "= urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason,", "body=body, headers=headers) redirects = 0 while response.status == 301 and", "new Cursor Object using the connection.\"\"\" if factory: return factory(self)", "self._ephemeral = None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__()", "scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http", "optional since not all databases provide transaction support. \"\"\" pass", "is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def", "_retry_request(self, method, uri, body=None, headers={}): tries = 10 while tries:", "( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import", "= scheme self.host = host self.port = port self._headers =", "port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme", "from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse", "forward; an Error (or subclass) exception will be raised if", "will be raised if any operation is attempted with the", "Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError,", "self.max_redirects): redirects += 1 uri = response.getheader('Location') location = urlparse(uri)", "self.port != location.port: self._connection.close() self.host = location.hostname self.port = location.port", "uri, body=body, headers=headers) return response def close(self): \"\"\"Close the connection", "InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def", "cls = HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection", "response.getheader('Location') is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or", "support transactions should implement this method with void functionality.\"\"\" pass", "the connection. Note that closing a connection without committing the", "body=None, headers={}): tries = 10 while tries: tries -= 1", "= host self.port = port self._headers = {} if not", "[] self.scheme = scheme self.host = host self.port = port", "self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return", "__del__(self): self.close() def commit(self): \"\"\"Database modules that do not support", "try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception:", "a connection without committing the changes first will cause an", "without committing the changes first will cause an implicit rollback", "disable=import-error from urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS,", "except Exception: if not tries: raise self._connection.close() self._connection = self._init_connection()", "return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout))", "self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status ==", "= self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response", "from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import", "pass def rollback(self): \"\"\"This method is optional since not all", "import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning,", "committing the changes first will cause an implicit rollback to", "cursor(self, factory=None): \"\"\"Return a new Cursor Object using the connection.\"\"\"", "% self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is None", "should implement this method with void functionality.\"\"\" pass def rollback(self):", "scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout", "not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method,", "to be performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None,", "if self.host != location.hostname or self.port != location.port: self._connection.close() self.host", ") def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0,", "scheme self.host = host self.port = port self._headers = {}", "None if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port", "= 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout =", "= detect_types & PARSE_COLNAMES self._ephemeral = None if scheme ==", "float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries = 10", "codecs import logging try: from http.client import HTTPConnection, HTTPSConnection except", "not support transactions should implement this method with void functionality.\"\"\"", "or self.port != location.port: self._connection.close() self.host = location.hostname self.port =", "try: from urllib.parse import urlparse except ImportError: # pylint: disable=import-error", "redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects =", "host self.port = port self._headers = {} if not (user", "self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme", "same applies to all cursor objects trying to use the", "pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from urllib.parse", "\\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects +=", "response def close(self): \"\"\"Close the connection now (rather than whenever", "if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral =", "if scheme == ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port =", "return self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection", "be unusable from this point forward; an Error (or subclass)", "unicode_literals import codecs import logging try: from http.client import HTTPConnection,", "from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error", "to all cursor objects trying to use the connection. Note", "rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is not None:", "\"\"\"This method is optional since not all databases provide transaction", "= location.hostname self.port = location.port self._connection = self._init_connection() response =", "is optional since not all databases provide transaction support. \"\"\"", "be performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None,", "= HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return", "\\ response.getheader('Location') is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS", "applies to all cursor objects trying to use the connection.", "urlparse import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from", "implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is not", "self.host != location.hostname or self.port != location.port: self._connection.close() self.host =", "{} if not (user is None or password is None):", "self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls =", "InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None,", "any operation is attempted with the connection. The same applies", "def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch a response,", "transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a new", "class Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError,", "is None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'),", "location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname self.port", "response.status, response.reason, uri) if self.host != location.hostname or self.port !=", "implement this method with void functionality.\"\"\" pass def rollback(self): \"\"\"This", "import codecs import logging try: from http.client import HTTPConnection, HTTPSConnection", "objects trying to use the connection. Note that closing a", "will cause an implicit rollback to be performed.\"\"\" self._connection.close() if", "def cursor(self, factory=None): \"\"\"Return a new Cursor Object using the", "Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import", "self._connection = self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'):", "Fetch a response, handling redirection. \"\"\" response = self._retry_request(method, uri,", "tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri,", "location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection =", "or redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location')", "uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s'", "self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES", "%s reason: '%s' location: '%s'\", response.status, response.reason, uri) if self.host", "self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if", "handling redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects", "1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason:", "cause an implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral", "void functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional since", "(self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1", "since not all databases provide transaction support. \"\"\" pass def", "databases provide transaction support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return", "password is None): self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user,", "response, handling redirection. \"\"\" response = self._retry_request(method, uri, body=body, headers=headers)", "The connection will be unusable from this point forward; an", "body=None, headers={}): \"\"\" Fetch a response, handling redirection. \"\"\" response", "301 and \\ response.getheader('Location') is not None and \\ (self.max_redirects", "cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme)", "password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types =", "redirects = 0 while response.status == 301 and \\ response.getheader('Location')", "now (rather than whenever .__del__() is called). The connection will", "connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host", "!= location.hostname or self.port != location.port: self._connection.close() self.host = location.hostname", "self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers) return response def", "is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}):", "= port self._headers = {} if not (user is None", "is not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects", "max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host = host", "performed.\"\"\" self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None)", "response.reason, uri) if self.host != location.hostname or self.port != location.port:", "method with void functionality.\"\"\" pass def rollback(self): \"\"\"This method is", "trying to use the connection. Note that closing a connection", "from .cursors import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited", "body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries:", "self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types &", "port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self,", "def rollback(self): \"\"\"This method is optional since not all databases", "uri, body=body, headers=headers) redirects = 0 while response.status == 301", "scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages =", "tries = 10 while tries: tries -= 1 try: self._connection.request(method,", "and \\ response.getheader('Location') is not None and \\ (self.max_redirects ==", "import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral", "# pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try: from", "changes first will cause an implicit rollback to be performed.\"\"\"", "httplib import HTTPConnection, HTTPSConnection try: from urllib.parse import urlparse except", "HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import", "import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class", "= self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while response.status", "an Error (or subclass) exception will be raised if any", "if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif self.scheme", "-= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse()", "UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri =", "do not support transactions should implement this method with void", "DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http',", "from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES,", "1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except", "codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types", "raised if any operation is attempted with the connection. The", "will be unusable from this point forward; an Error (or", "port self._headers = {} if not (user is None or", "'%s' location: '%s'\", response.status, response.reason, uri) if self.host != location.hostname", "connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types", "logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError: #", "urllib.parse import urlparse except ImportError: # pylint: disable=import-error from urlparse", "= HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else:", "self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if scheme", "HTTPSConnection except ImportError: # pylint: disable=import-error from httplib import HTTPConnection,", "self._connection.close() if self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral", "headers={}): tries = 10 while tries: tries -= 1 try:", "import unicode_literals import codecs import logging try: from http.client import", "redirects += 1 uri = response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status:", ".constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor from", "\"\"\"Close the connection now (rather than whenever .__del__() is called).", "use the connection. Note that closing a connection without committing", "def commit(self): \"\"\"Database modules that do not support transactions should", "not (user is None or password is None): self._headers['Authorization'] =", "while tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers,", "method, uri, body=None, headers={}): \"\"\" Fetch a response, handling redirection.", "None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects):", "if not tries: raise self._connection.close() self._connection = self._init_connection() def _fetch_response(self,", "method is optional since not all databases provide transaction support.", "PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None if", "redirects < self.max_redirects): redirects += 1 uri = response.getheader('Location') location", "\"\"\"Database modules that do not support transactions should implement this", "elif self.scheme == 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported", "None def __del__(self): self.close() def commit(self): \"\"\"Database modules that do", "else: return Cursor(self) def execute(self, *args, **kwargs): return self.cursor().execute(*args, **kwargs)", "== ':memory:': self._ephemeral = _EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection", "an implicit rollback to be performed.\"\"\" self._connection.close() if self._ephemeral is", "not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self):", "operation is attempted with the connection. The same applies to", "uri, body=None, headers={}): tries = 10 while tries: tries -=", "the connection now (rather than whenever .__del__() is called). The", "':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls =", "= response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location:", "(rather than whenever .__del__() is called). The connection will be", "close(self): \"\"\"Close the connection now (rather than whenever .__del__() is", "urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason, uri)", "= None def __del__(self): self.close() def commit(self): \"\"\"Database modules that", ".exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError,", "all databases provide transaction support. \"\"\" pass def cursor(self, factory=None):", "' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects", "'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout", "import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from httplib", "tries: tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers))", "self._connection.close() self.host = location.hostname self.port = location.port self._connection = self._init_connection()", "< self.max_redirects): redirects += 1 uri = response.getheader('Location') location =", "None, None) self._ephemeral = None def __del__(self): self.close() def commit(self):", "uri, body=None, headers={}): \"\"\" Fetch a response, handling redirection. \"\"\"", "Object using the connection.\"\"\" if factory: return factory(self) else: return", "& PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral = None", "\"\"\" Fetch a response, handling redirection. \"\"\" response = self._retry_request(method,", "this point forward; an Error (or subclass) exception will be", "if self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri,", "cls(self.host, port=self.port, timeout=None if self.connect_timeout is None else float(self.connect_timeout)) def", "import logging try: from http.client import HTTPConnection, HTTPSConnection except ImportError:", "detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types &", "Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None if", ") from .cursors import Cursor from ._ephemeral import EphemeralRqlited as", "ImportError: # pylint: disable=import-error from httplib import HTTPConnection, HTTPSConnection try:", "pylint: disable=import-error from urlparse import urlparse from .constants import (", "self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if", "transactions should implement this method with void functionality.\"\"\" pass def", "all cursor objects trying to use the connection. Note that", "closing a connection without committing the changes first will cause", "not None and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects <", "response = self._retry_request(method, uri, body=body, headers=headers) return response def close(self):", "else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port,", "raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host, port=self.port, timeout=None", "while response.status == 301 and \\ response.getheader('Location') is not None", "try: from http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint:", "self._retry_request(method, uri, body=body, headers=headers) return response def close(self): \"\"\"Close the", "response.status == 301 and \\ response.getheader('Location') is not None and", "called). The connection will be unusable from this point forward;", "self._ephemeral is not None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None", "response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0 while", "<reponame>zmedico/pyrqlite from __future__ import unicode_literals import codecs import logging try:", "HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r' % self.scheme) return cls(self.host,", "and \\ (self.max_redirects == UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects", "modules that do not support transactions should implement this method", "is attempted with the connection. The same applies to all", "& PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral", "UNLIMITED_REDIRECTS, ) from .cursors import Cursor from ._ephemeral import EphemeralRqlited", "self.port = port self._headers = {} if not (user is", "def close(self): \"\"\"Close the connection now (rather than whenever .__del__()", "%r' % self.scheme) return cls(self.host, port=self.port, timeout=None if self.connect_timeout is", "connection.\"\"\" if factory: return factory(self) else: return Cursor(self) def execute(self,", "from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import Cursor", "detect_types & PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:':", "functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional since not", "DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self,", "HTTPConnection elif self.scheme == 'https': cls = HTTPSConnection else: raise", "return response def close(self): \"\"\"Close the connection now (rather than", "= detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral", "self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme", "= max_redirects self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES", "= 10 while tries: tries -= 1 try: self._connection.request(method, uri,", "password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme", "def __del__(self): self.close() def commit(self): \"\"\"Database modules that do not", "0 while response.status == 301 and \\ response.getheader('Location') is not", "detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types & PARSE_COLNAMES self._ephemeral =", "detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages = [] self.scheme = scheme self.host =", "= {} if not (user is None or password is", "IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001,", ".__del__() is called). The connection will be unusable from this", "point forward; an Error (or subclass) exception will be raised", "# pylint: disable=import-error from urlparse import urlparse from .constants import", "self._ephemeral = None def __del__(self): self.close() def commit(self): \"\"\"Database modules", "self.port = location.port self._connection = self._init_connection() response = self._retry_request(method, uri,", "be raised if any operation is attempted with the connection.", "uri, body=body, headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not", "unusable from this point forward; an Error (or subclass) exception", "== 301 and \\ response.getheader('Location') is not None and \\", "= self._ephemeral.http self._connection = self._init_connection() def _init_connection(self): if self.scheme in", "not all databases provide transaction support. \"\"\" pass def cursor(self,", "location.port self._connection = self._init_connection() response = self._retry_request(method, uri, body=body, headers=headers)", "location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status,", "is None or password is None): self._headers['Authorization'] = 'Basic '", "location: '%s'\", response.status, response.reason, uri) if self.host != location.hostname or", "urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors import", "attempted with the connection. The same applies to all cursor", "._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES", "http.client import HTTPConnection, HTTPSConnection except ImportError: # pylint: disable=import-error from", "the connection.\"\"\" if factory: return factory(self) else: return Cursor(self) def", "factory=None): \"\"\"Return a new Cursor Object using the connection.\"\"\" if", "def _retry_request(self, method, uri, body=None, headers={}): tries = 10 while", "!= location.port: self._connection.close() self.host = location.hostname self.port = location.port self._connection", "('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https': cls", "PARSE_COLNAMES class Connection(object): from .exceptions import ( Warning, Error, InterfaceError,", "except ImportError: # pylint: disable=import-error from urlparse import urlparse from", "None) self._ephemeral = None def __del__(self): self.close() def commit(self): \"\"\"Database", "response.getheader('Location') location = urlparse(uri) logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\",", "that do not support transactions should implement this method with", "support. \"\"\" pass def cursor(self, factory=None): \"\"\"Return a new Cursor", "to use the connection. Note that closing a connection without", "body=body, headers=headers) return response def close(self): \"\"\"Close the connection now", "+ \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout = connect_timeout self.max_redirects =", "PARSE_COLNAMES self._ephemeral = None if scheme == ':memory:': self._ephemeral =", "self.detect_types = detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames =", "in ('http', ':memory:'): cls = HTTPConnection elif self.scheme == 'https':", "== UNLIMITED_REDIRECTS or redirects < self.max_redirects): redirects += 1 uri", "self._connection.close() self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}):", "connection. The same applies to all cursor objects trying to", "tries -= 1 try: self._connection.request(method, uri, body=body, headers=dict(self._headers, **headers)) return", "( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError,", "self._connection = self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\"", "(user is None or password is None): self._headers['Authorization'] = 'Basic", "def _init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection", "def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS):", "connection now (rather than whenever .__del__() is called). The connection", "pass def cursor(self, factory=None): \"\"\"Return a new Cursor Object using", "the connection. The same applies to all cursor objects trying", "with void functionality.\"\"\" pass def rollback(self): \"\"\"This method is optional", "(or subclass) exception will be raised if any operation is", "= detect_types self.parse_decltypes = detect_types & PARSE_DECLTYPES self.parse_colnames = detect_types", "None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None, headers={}): tries", "import ( Warning, Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError,", "self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close() def", "\"\"\" response = self._retry_request(method, uri, body=body, headers=headers) redirects = 0", "OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, ) def __init__(self, scheme='http', host='localhost',", "Connection(object): from .exceptions import ( Warning, Error, InterfaceError, DatabaseError, DataError,", "None or password is None): self._headers['Authorization'] = 'Basic ' +", "HTTPSConnection try: from urllib.parse import urlparse except ImportError: # pylint:", "_EphemeralRqlited().__enter__() self.host, self.port = self._ephemeral.http self._connection = self._init_connection() def _init_connection(self):", "_init_connection(self): if self.scheme in ('http', ':memory:'): cls = HTTPConnection elif", "Error, InterfaceError, DatabaseError, DataError, OperationalError, IntegrityError, InternalError, ProgrammingError, NotSupportedError, )", "connection will be unusable from this point forward; an Error", "EphemeralRqlited as _EphemeralRqlited from .extensions import PARSE_DECLTYPES, PARSE_COLNAMES class Connection(object):", "**headers)) return self._connection.getresponse() except Exception: if not tries: raise self._connection.close()", "connection without committing the changes first will cause an implicit", "this method with void functionality.\"\"\" pass def rollback(self): \"\"\"This method", "Error (or subclass) exception will be raised if any operation", "self.connect_timeout = connect_timeout self.max_redirects = max_redirects self.detect_types = detect_types self.parse_decltypes", "using the connection.\"\"\" if factory: return factory(self) else: return Cursor(self)", "NotSupportedError, ) def __init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None,", "headers=dict(self._headers, **headers)) return self._connection.getresponse() except Exception: if not tries: raise", "whenever .__del__() is called). The connection will be unusable from", "than whenever .__del__() is called). The connection will be unusable", "subclass) exception will be raised if any operation is attempted", "uri) if self.host != location.hostname or self.port != location.port: self._connection.close()", "self.connect_timeout is None else float(self.connect_timeout)) def _retry_request(self, method, uri, body=None,", "'%s'\", response.status, response.reason, uri) if self.host != location.hostname or self.port", "import urlparse from .constants import ( UNLIMITED_REDIRECTS, ) from .cursors", "headers=headers) redirects = 0 while response.status == 301 and \\", "logging.getLogger(__name__).debug(\"status: %s reason: '%s' location: '%s'\", response.status, response.reason, uri) if", "self._headers['Authorization'] = 'Basic ' + \\ codecs.encode('{}:{}'.format(user, password).encode('utf-8'), 'base64').decode('utf-8').rstrip('\\n') self.connect_timeout", "self._connection.getresponse() except Exception: if not tries: raise self._connection.close() self._connection =", "if not (user is None or password is None): self._headers['Authorization']", "= self._init_connection() def _init_connection(self): if self.scheme in ('http', ':memory:'): cls", "== 'https': cls = HTTPSConnection else: raise Connection.ProgrammingError('Unsupported scheme %r'", "__init__(self, scheme='http', host='localhost', port=4001, user=None, password=<PASSWORD>, connect_timeout=None, detect_types=0, max_redirects=UNLIMITED_REDIRECTS): self.messages", "import Cursor from ._ephemeral import EphemeralRqlited as _EphemeralRqlited from .extensions", "= self._init_connection() def _fetch_response(self, method, uri, body=None, headers={}): \"\"\" Fetch", "None: self._ephemeral.__exit__(None, None, None) self._ephemeral = None def __del__(self): self.close()" ]
[ "* 8.2 price_trucks = trucks * 2 total_price = price_puzzles", "price_minions + price_trucks if total_toys >= 50: total_price = total_price", "total_price = total_price - rent if total_price >= price: print(f\"Yes!", "left.\") else: print(f\"Not enough money! {(price - total_price):.2f} lv needed.\")", "(total_price * 0.25) rent = total_price * 0.1 total_price =", "total_toys = puzzles + dolls + bears + minions +", "price_bears + price_minions + price_trucks if total_toys >= 50: total_price", "trucks * 2 total_price = price_puzzles + price_dolls + price_bears", "dolls + bears + minions + trucks price_puzzles = puzzles", "puzzles * 2.6 price_dolls = dolls * 3 price_bears =", "= total_price - rent if total_price >= price: print(f\"Yes! {(total_price", "price_dolls + price_bears + price_minions + price_trucks if total_toys >=", "* 4.1 price_minions = minions * 8.2 price_trucks = trucks", "int(input()) minions = int(input()) trucks = int(input()) total_toys = puzzles", "puzzles + dolls + bears + minions + trucks price_puzzles", ">= 50: total_price = total_price - (total_price * 0.25) rent", "total_price = price_puzzles + price_dolls + price_bears + price_minions +", "int(input()) bears = int(input()) minions = int(input()) trucks = int(input())", "dolls = int(input()) bears = int(input()) minions = int(input()) trucks", "price = float(input()) puzzles = int(input()) dolls = int(input()) bears", "bears = int(input()) minions = int(input()) trucks = int(input()) total_toys", "if total_toys >= 50: total_price = total_price - (total_price *", "int(input()) dolls = int(input()) bears = int(input()) minions = int(input())", "rent = total_price * 0.1 total_price = total_price - rent", "total_price * 0.1 total_price = total_price - rent if total_price", "= int(input()) dolls = int(input()) bears = int(input()) minions =", "- rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f}", "minions * 8.2 price_trucks = trucks * 2 total_price =", "+ price_minions + price_trucks if total_toys >= 50: total_price =", "float(input()) puzzles = int(input()) dolls = int(input()) bears = int(input())", "= minions * 8.2 price_trucks = trucks * 2 total_price", "* 0.1 total_price = total_price - rent if total_price >=", "price_puzzles = puzzles * 2.6 price_dolls = dolls * 3", "minions + trucks price_puzzles = puzzles * 2.6 price_dolls =", "- (total_price * 0.25) rent = total_price * 0.1 total_price", "= total_price - (total_price * 0.25) rent = total_price *", "* 2.6 price_dolls = dolls * 3 price_bears = bears", ">= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not", "int(input()) total_toys = puzzles + dolls + bears + minions", "minions = int(input()) trucks = int(input()) total_toys = puzzles +", "* 2 total_price = price_puzzles + price_dolls + price_bears +", "dolls * 3 price_bears = bears * 4.1 price_minions =", "total_toys >= 50: total_price = total_price - (total_price * 0.25)", "price_dolls = dolls * 3 price_bears = bears * 4.1", "lv left.\") else: print(f\"Not enough money! {(price - total_price):.2f} lv", "puzzles = int(input()) dolls = int(input()) bears = int(input()) minions", "price_trucks if total_toys >= 50: total_price = total_price - (total_price", "price_minions = minions * 8.2 price_trucks = trucks * 2", "total_price - rent if total_price >= price: print(f\"Yes! {(total_price -", "= int(input()) minions = int(input()) trucks = int(input()) total_toys =", "4.1 price_minions = minions * 8.2 price_trucks = trucks *", "price_bears = bears * 4.1 price_minions = minions * 8.2", "= trucks * 2 total_price = price_puzzles + price_dolls +", "price_puzzles + price_dolls + price_bears + price_minions + price_trucks if", "= puzzles * 2.6 price_dolls = dolls * 3 price_bears", "{(total_price - price):.2f} lv left.\") else: print(f\"Not enough money! {(price", "+ minions + trucks price_puzzles = puzzles * 2.6 price_dolls", "= puzzles + dolls + bears + minions + trucks", "= bears * 4.1 price_minions = minions * 8.2 price_trucks", "= int(input()) trucks = int(input()) total_toys = puzzles + dolls", "bears * 4.1 price_minions = minions * 8.2 price_trucks =", "* 3 price_bears = bears * 4.1 price_minions = minions", "+ price_bears + price_minions + price_trucks if total_toys >= 50:", "print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not enough money!", "0.1 total_price = total_price - rent if total_price >= price:", "50: total_price = total_price - (total_price * 0.25) rent =", "= int(input()) total_toys = puzzles + dolls + bears +", "+ price_trucks if total_toys >= 50: total_price = total_price -", "<filename>PythonBasics/ConditionalStatements/Exercise/toy_shop.py<gh_stars>0 price = float(input()) puzzles = int(input()) dolls = int(input())", "+ price_dolls + price_bears + price_minions + price_trucks if total_toys", "= float(input()) puzzles = int(input()) dolls = int(input()) bears =", "+ trucks price_puzzles = puzzles * 2.6 price_dolls = dolls", "3 price_bears = bears * 4.1 price_minions = minions *", "total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else:", "2 total_price = price_puzzles + price_dolls + price_bears + price_minions", "= total_price * 0.1 total_price = total_price - rent if", "= dolls * 3 price_bears = bears * 4.1 price_minions", "+ bears + minions + trucks price_puzzles = puzzles *", "bears + minions + trucks price_puzzles = puzzles * 2.6", "8.2 price_trucks = trucks * 2 total_price = price_puzzles +", "price: print(f\"Yes! {(total_price - price):.2f} lv left.\") else: print(f\"Not enough", "if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv left.\")", "rent if total_price >= price: print(f\"Yes! {(total_price - price):.2f} lv", "price_trucks = trucks * 2 total_price = price_puzzles + price_dolls", "* 0.25) rent = total_price * 0.1 total_price = total_price", "0.25) rent = total_price * 0.1 total_price = total_price -", "trucks = int(input()) total_toys = puzzles + dolls + bears", "total_price - (total_price * 0.25) rent = total_price * 0.1", "= int(input()) bears = int(input()) minions = int(input()) trucks =", "trucks price_puzzles = puzzles * 2.6 price_dolls = dolls *", "total_price = total_price - (total_price * 0.25) rent = total_price", "= price_puzzles + price_dolls + price_bears + price_minions + price_trucks", "int(input()) trucks = int(input()) total_toys = puzzles + dolls +", "price):.2f} lv left.\") else: print(f\"Not enough money! {(price - total_price):.2f}", "+ dolls + bears + minions + trucks price_puzzles =", "2.6 price_dolls = dolls * 3 price_bears = bears *", "- price):.2f} lv left.\") else: print(f\"Not enough money! {(price -" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s')))", "may obtain # a copy of the License at #", "ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache", "# # Licensed under the Apache License, Version 2.0 (the", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "is used for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s'", "cache that is used for keystone tokens lookup.\"\"\" _cache =", "'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good',", "distributed under the License is distributed on an \"AS IS\"", "'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles':", "= None self.set_value = None self.token_expiration = None def get(self,", "import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object):", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "\"\"\"Fake cache that is used for keystone tokens lookup.\"\"\" _cache", "obtain # a copy of the License at # #", "[{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access':", "applicable law or agreed to in writing, software # distributed", "API service. \"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>'", "'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } },", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1',", "# vim: tabstop=4 shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*-", "Version 2.0 (the \"License\"); you may # not use this", "# -*- encoding: utf-8 -*- # # Licensed under the", "specific language governing permissions and limitations # under the License.", "permissions and limitations # under the License. \"\"\" Utils for", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "testing the API service. \"\"\" import datetime import json ADMIN_TOKEN", "'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] }", "} } def __init__(self): self.set_key = None self.set_value = None", "= None self.token_expiration = None def get(self, key): dt =", "'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } }", "'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910',", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "'<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used for keystone", "'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}]", "self.set_value = None self.token_expiration = None def get(self, key): dt", "self.token_expiration = None def get(self, key): dt = datetime.datetime.now() +", "the License. You may obtain # a copy of the", "the License. \"\"\" Utils for testing the API service. \"\"\"", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "Utils for testing the API service. \"\"\" import datetime import", "You may obtain # a copy of the License at", "and limitations # under the License. \"\"\" Utils for testing", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "governing permissions and limitations # under the License. \"\"\" Utils", "'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } }", "set(self, key, value, timeout=None): self.set_value = value self.set_key = key", "'roles': [{'name': 'Member'}] } } } } def __init__(self): self.set_key", "'<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is", "return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value =", "{ 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN},", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "{ 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name':", "'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good',", "}, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token':", "__init__(self): self.set_key = None self.set_value = None self.token_expiration = None", "MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies',", "key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def", "json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake", "either express or implied. See the # License for the", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "} def __init__(self): self.set_key = None self.set_value = None self.token_expiration", "'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } } }", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "None self.token_expiration = None def get(self, key): dt = datetime.datetime.now()", "datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value", "datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class", "'123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s'", "'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user':", "self.set_key = None self.set_value = None self.token_expiration = None def", "'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user':", "you may # not use this file except in compliance", "for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN:", "MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2',", "def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key),", "\"License\"); you may # not use this file except in", "dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self,", "-*- encoding: utf-8 -*- # # Licensed under the Apache", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "under the License. \"\"\" Utils for testing the API service.", "\"\"\" Utils for testing the API service. \"\"\" import datetime", "compliance with the License. You may obtain # a copy", "the Apache License, Version 2.0 (the \"License\"); you may #", "None self.set_value = None self.token_expiration = None def get(self, key):", "'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: { 'access': {", "'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles':", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "[{'name': 'Member'}] } } } } def __init__(self): self.set_key =", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "See the # License for the specific language governing permissions", "limitations # under the License. \"\"\" Utils for testing the", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value = value self.set_key", "-*- # # Licensed under the Apache License, Version 2.0", "} } } } def __init__(self): self.set_key = None self.set_value", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "encoding: utf-8 -*- # # Licensed under the Apache License,", "the # License for the specific language governing permissions and", "# under the License. \"\"\" Utils for testing the API", "% MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN}, 'user': {'id':", "utf-8 -*- # # Licensed under the Apache License, Version", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "License. \"\"\" Utils for testing the API service. \"\"\" import", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "service. \"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN", "class FakeMemcache(object): \"\"\"Fake cache that is used for keystone tokens", "_cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token':", "\"\"\" import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN =", "{'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name':", "file except in compliance with the License. You may obtain", "'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1',", "} } } def __init__(self): self.set_key = None self.set_value =", "{'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name':", "vim: tabstop=4 shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*- #", "% ADMIN_TOKEN: { 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id':", "for the specific language governing permissions and limitations # under", "law or agreed to in writing, software # distributed under", "MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "{'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName':", "{'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName':", "= '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that is used for", "}, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id': MEMBER_TOKEN},", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None): self.set_value = value", "implied. See the # License for the specific language governing", "the API service. \"\"\" import datetime import json ADMIN_TOKEN =", "datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value,", "None def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5) return", "'user_id2', 'name': 'user-good', 'tenantId': 'project-good', 'tenantName': 'goodies', 'roles': [{'name': 'Member'}]", "'Member'}] } } } } def __init__(self): self.set_key = None", "License. You may obtain # a copy of the License", "used for keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' %", "def __init__(self): self.set_key = None self.set_value = None self.token_expiration =", "for testing the API service. \"\"\" import datetime import json", "tabstop=4 shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*- # #", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "FakeMemcache(object): \"\"\"Fake cache that is used for keystone tokens lookup.\"\"\"", "lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access': {", "def set(self, key, value, timeout=None): self.set_value = value self.set_key =", "# Unless required by applicable law or agreed to in", "ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant',", "} }, 'tokens/%s' % MEMBER_TOKEN: { 'access': { 'token': {'id':", "+ datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key, value, timeout=None):", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "'goodies', 'roles': [{'name': 'Member'}] } } } } def __init__(self):", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "import datetime import json ADMIN_TOKEN = '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>'", "{ 'access': { 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name':", "'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, }", "tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: { 'access':", "softtabstop=4 # -*- encoding: utf-8 -*- # # Licensed under", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "= { 'tokens/%s' % ADMIN_TOKEN: { 'access': { 'token': {'id':", "or agreed to in writing, software # distributed under the", "language governing permissions and limitations # under the License. \"\"\"", "required by applicable law or agreed to in writing, software", "that is used for keystone tokens lookup.\"\"\" _cache = {", "keystone tokens lookup.\"\"\" _cache = { 'tokens/%s' % ADMIN_TOKEN: {", "'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN:", "= None def get(self, key): dt = datetime.datetime.now() + datetime.timedelta(minutes=5)", "'name': 'user_name1', 'tenantId': '123i2910', 'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] },", "= '<PASSWORD>' MEMBER_TOKEN = '<PASSWORD>' class FakeMemcache(object): \"\"\"Fake cache that", "{ 'token': {'id': MEMBER_TOKEN}, 'user': {'id': 'user_id2', 'name': 'user-good', 'tenantId':", "'tenantName': 'goodies', 'roles': [{'name': 'Member'}] } } } } def", "shiftwidth=4 softtabstop=4 # -*- encoding: utf-8 -*- # # Licensed", "'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' % MEMBER_TOKEN: {", "'tenantName': 'mytenant', 'roles': [{'name': 'admin'}] }, } }, 'tokens/%s' %", "= datetime.datetime.now() + datetime.timedelta(minutes=5) return json.dumps((self._cache.get(key), dt.strftime('%s'))) def set(self, key,", "{ 'token': {'id': ADMIN_TOKEN}, 'user': {'id': 'user_id1', 'name': 'user_name1', 'tenantId':", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content =", "StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired,", "class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid", "import datetime from flask_wtf import FlaskForm from wtforms import (", "must be greater than or equal to date started.\" )", "to date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\")", "for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation", "class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating =", "FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField,", "StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title =", "ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\",", "format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data", "or equal to date started\") raise ValidationError( \"Date finished must", "TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError,", "self.data = None raise ValueError(self.gettext(\"Not a valid date value\")) class", "import FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField,", "ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid date value\"))", "setting read dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name", "Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")],", "SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\",", "read dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name =", "must be greater than or equal to date started\") raise", "PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class", "TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\",", "wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from", "be greater than or equal to date started\") raise ValidationError(", "self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid", "validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must", "= datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not", "# Bypasses wtForms validation for blank datetime field. if valuelist:", "for blank datetime field. if valuelist: date_str = \" \".join(valuelist).strip()", "be greater than or equal to date started.\" ) elif", "= None return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError:", "date_finished): if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date", "self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must", "= StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title", "Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation for", "values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms validation for blank", "validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data:", "NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data:", "Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished):", "started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If", "Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], )", "raise ValidationError( \"Date finished must be greater than or equal", "valuelist): # Bypasses wtForms validation for blank datetime field. if", "review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\",", "\" \".join(valuelist).strip() if date_str == \"\": self.data = None return", "date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must be greater", "print(\"missing date\") raise ValidationError(\"If setting read dates, both dates are", "import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to", "ValidationError(\"If setting read dates, both dates are required.\") class EditProfileForm(FlaskForm):", "class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def", "equal to date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing", "from wtforms import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, )", "email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\",", "and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished must be", "= NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and", "\"\": self.data = None return try: self.data = datetime.datetime.strptime(date_str, self.format)", "StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password =", "elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read", "rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\")", "search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()])", "date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates, both dates", "Bypasses wtForms validation for blank datetime field. if valuelist: date_str", "valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class", "ValidationError( \"Date finished must be greater than or equal to", "self.data = None return try: self.data = datetime.datetime.strptime(date_str, self.format) except", "if self.date_started.data and date_finished.data: if self.date_started.data > date_finished.data: print(\"Date finished", "StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished", "datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise ValueError(self.gettext(\"Not a", "Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null", "dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email", "password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password", "greater than or equal to date started\") raise ValidationError( \"Date", "date started\") raise ValidationError( \"Date finished must be greater than", "validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password = PasswordField(\"Confirm Password\", validators=[])", "validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField(", "\"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self, valuelist):", "DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email,", "Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if", "or equal to date started.\" ) elif self.date_started.data or date_finished.data:", "are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email =", "than or equal to date started\") raise ValidationError( \"Date finished", "EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email", "flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField, DateTimeField,", "\"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password = PasswordField(\"Confirm Password\",", "None return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data", "<reponame>thewordisbird/bookshelf import datetime from flask_wtf import FlaskForm from wtforms import", "date_str == \"\": self.data = None return try: self.data =", "except ValueError: self.data = None raise ValueError(self.gettext(\"Not a valid date", ") from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField):", "None raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search", "from wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify", "= None raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm):", "date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if self.date_started.data", "valuelist: date_str = \" \".join(valuelist).strip() if date_str == \"\": self.data", "= StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password", "= TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date", "dates, both dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\",", "equal to date started\") raise ValidationError( \"Date finished must be", "started\") raise ValidationError( \"Date finished must be greater than or", "NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\" def process_formdata(self,", "print(\"Date finished must be greater than or equal to date", "if date_str == \"\": self.data = None return try: self.data", "DateField to allow for Null values\"\"\" def process_formdata(self, valuelist): #", "= HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started", "wtForms validation for blank datetime field. if valuelist: date_str =", "a valid date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()])", "validation for blank datetime field. if valuelist: date_str = \"", "= PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password =", "\"Date finished must be greater than or equal to date", "to allow for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses", "if self.date_started.data > date_finished.data: print(\"Date finished must be greater than", "NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self,", "self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates,", "blank datetime field. if valuelist: date_str = \" \".join(valuelist).strip() if", "value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm): rating", "= StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\",", "date_finished.data: print(\"Date finished must be greater than or equal to", "StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")]) password = PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords", "allow for Null values\"\"\" def process_formdata(self, valuelist): # Bypasses wtForms", "ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for", "field. if valuelist: date_str = \" \".join(valuelist).strip() if date_str ==", "from flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField,", "EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow for Null values\"\"\"", "> date_finished.data: print(\"Date finished must be greater than or equal", ") elif self.date_started.data or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting", "validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date", "import ( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators", "DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField to allow", "greater than or equal to date started.\" ) elif self.date_started.data", "wtforms.validators import DataRequired, ValidationError, Email, EqualTo class NullableDateTimeField(DateTimeField): \"\"\"Modify DateField", "def validate_date_finished(self, date_finished): if self.date_started.data and date_finished.data: if self.date_started.data >", "date started.\" ) elif self.date_started.data or date_finished.data: print(\"missing date\") raise", "\".join(valuelist).strip() if date_str == \"\": self.data = None return try:", "PasswordField( \"Password\", validators=[EqualTo(\"<PASSWORD>\", message=\"Passwords must match.\")], ) confirm_password = PasswordField(\"Confirm", "date\") raise ValidationError(\"If setting read dates, both dates are required.\")", "date value\")) class SearchForm(FlaskForm): search = StringField(\"Search\", validators=[DataRequired()]) class ReviewForm(FlaskForm):", "display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\", validators=[Email(message=\"Invalid Email Address.\")])", "review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished =", "validators=[DataRequired()]) class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\")", "def process_formdata(self, valuelist): # Bypasses wtForms validation for blank datetime", "finished must be greater than or equal to date started\")", "self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None raise", "return try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data =", "date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\")", "format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def validate_date_finished(self, date_finished): if", "try: self.data = datetime.datetime.strptime(date_str, self.format) except ValueError: self.data = None", "== \"\": self.data = None return try: self.data = datetime.datetime.strptime(date_str,", "both dates are required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[])", "raise ValueError(self.gettext(\"Not a valid date value\")) class SearchForm(FlaskForm): search =", "finished must be greater than or equal to date started.\"", "date_str = \" \".join(valuelist).strip() if date_str == \"\": self.data =", "= \" \".join(valuelist).strip() if date_str == \"\": self.data = None", "raise ValidationError(\"If setting read dates, both dates are required.\") class", "datetime from flask_wtf import FlaskForm from wtforms import ( StringField,", "= NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\") date_finished = NullableDateTimeField(\"Date Finished\", format=\"%m/%d/%Y\") def", "class ReviewForm(FlaskForm): rating = HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content", "to date started\") raise ValidationError( \"Date finished must be greater", "self.date_started.data > date_finished.data: print(\"Date finished must be greater than or", "HiddenField(\"Rating\", validators=[DataRequired()]) review_title = StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started =", "datetime field. if valuelist: date_str = \" \".join(valuelist).strip() if date_str", "required.\") class EditProfileForm(FlaskForm): display_name = StringField(\"Name\", validators=[]) email = StringField(\"Email\",", "HiddenField, PasswordField, ) from wtforms.validators import DataRequired, ValidationError, Email, EqualTo", "if valuelist: date_str = \" \".join(valuelist).strip() if date_str == \"\":", "= StringField(\"Headline\") review_content = TextAreaField(\"Review\") date_started = NullableDateTimeField(\"Date Started\", format=\"%m/%d/%Y\")", "process_formdata(self, valuelist): # Bypasses wtForms validation for blank datetime field.", "than or equal to date started.\" ) elif self.date_started.data or", "( StringField, TextAreaField, DateTimeField, HiddenField, PasswordField, ) from wtforms.validators import", "or date_finished.data: print(\"missing date\") raise ValidationError(\"If setting read dates, both" ]
[ "normalizate #tipul de normalizare este setat implicit la l2 scaler", "definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions =", "normalizare este setat implicit la l2 scaler = None if", "by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" #", "= pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim", "sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] #", "pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples", "Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels =", "sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a obtine valori", "header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam", "matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV", "header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram", "'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm = type)", "datelor pentru a obtine valori numerice din text from sklearn.metrics", "scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler()", "setat implicit la l2 scaler = None if type ==", "is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy", "import numpy as np import pandas as pd # pandas", "scaler = preprocessing.MinMaxScaler() elif type == 'l1' or type ==", "numerice din text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea", "cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele", "\") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export", "preprocessing.MinMaxScaler() elif type == 'l1' or type == 'l2': scaler", "data frame-ul intr-un vector train_labels = train_labels[:,1] # pastram doar", "validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt',", "norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features)", "fisierelor from sklearn import preprocessing from sklearn import svm #", "import pandas as pd # pandas pentru citirea fisierelor from", "test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia", "= validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None,", "functia care intoarce datele normalizate #tipul de normalizare este setat", "https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as np import", "print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format", "modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul", "obtine valori numerice din text from sklearn.metrics import classification_report, confusion_matrix", "# convertim data frame-ul intr-un vector train_labels = train_labels[:,1] #", "normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul", "= model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification report:", "# importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor", "pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples", "validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples =", "type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1'", "not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return", "modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a", "frame-ul intr-un vector train_labels = train_labels[:,1] # pastram doar etichetele", "validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110)", "# Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features", "# predictie pe datele de test print(\"Classification report: \") print(classification_report(validation_labels,", "numpy as np import pandas as pd # pandas pentru", "validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples", "datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix:", "= test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] # salvam", "== 'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler", "#tipul de normalizare este setat implicit la l2 scaler =", "== 'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm =", "test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label", "scaler = preprocessing.Normalizer(norm = type) if scaler is not None:", "pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1]", "TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples)", "test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples)", "utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is", "a obtine valori numerice din text from sklearn.metrics import classification_report,", "test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele", "validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels", "datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy()", "citirea fisierelor from sklearn import preprocessing from sklearn import svm", "train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() #", "validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python')", "de invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele de", "modelarea datelor pentru a obtine valori numerice din text from", "= pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples =", "= test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'): #", "# salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele def", "at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as np", "train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None,", "-*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is located", "cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy()", "salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care intoarce", "train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None,", "testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM", "C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul de", "# procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie pe", "import svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer #", "model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions}", "importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru", "def normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele normalizate", "# pandas pentru citirea fisierelor from sklearn import preprocessing from", "'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max': scaler =", "print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in format CSV test_export =", "coding: utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file", "type) if scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data)", "implicit la l2 scaler = None if type == 'standard':", "\"\"\" # Importarea librariilor import numpy as np import pandas", "# pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python')", "# salvam cuvintele def normalize_data(train_data, test_data, type='l2'): # functia care", "doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples =", "pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0]", "= normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear',", "Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor", "datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples)", "header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram", "la l2 scaler = None if type == 'standard': scaler", "preprocessing.Normalizer(norm = type) if scaler is not None: scaler.fit(train_data) scaled_train_data", "pd # pandas pentru citirea fisierelor from sklearn import preprocessing", "sklearn import svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer", "= TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features =", "as pd # pandas pentru citirea fisierelor from sklearn import", "= train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t',", "# Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels", "elif type == 'l1' or type == 'l2': scaler =", "== 'l2': scaler = preprocessing.Normalizer(norm = type) if scaler is", "None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data,", "from sklearn.feature_extraction.text import TfidfVectorizer # modelarea datelor pentru a obtine", "Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw", "= vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features)", "type == 'standard': scaler = preprocessing.StandardScaler() elif type == 'min_max':", "= scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return", "datelor in format CSV test_export = {'id':label,'label':test_predictions} data_f = pd.DataFrame(test_export)", "gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare", "or type == 'l2': scaler = preprocessing.Normalizer(norm = type) if", "in format CSV test_export = {'id':label,'label':test_predictions} data_f = pd.DataFrame(test_export) data_f.to_csv('test_submission.csv',index=False)", "= pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples =", "model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels)", "vector train_labels = train_labels[:,1] # pastram doar etichetele train_samples =", "doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples =", "None if type == 'standard': scaler = preprocessing.StandardScaler() elif type", "file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import", "located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea librariilor import numpy as", "de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \")", "\"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original file is located at", "pentru a obtine valori numerice din text from sklearn.metrics import", "test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data, type='l2'):", "preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type", "engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele", "header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam", "validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele", "train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt',", "# -*- coding: utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory.", "# pastram doar cuvintele validation_samples = pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python')", "train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples =", "engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele", "test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels,", "train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features =", "intoarce datele normalizate #tipul de normalizare este setat implicit la", "test_samples = test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples", "Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\" # Importarea", "scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data", "else: return train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer()", "normalize_data(train_data, test_data, type='l2'): # functia care intoarce datele normalizate #tipul", "np import pandas as pd # pandas pentru citirea fisierelor", "scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data,", "from sklearn import svm # importarea modelului from sklearn.feature_extraction.text import", "text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels", "header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un", "test_data, type='l2'): # functia care intoarce datele normalizate #tipul de", "sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label = test_samples[:,0] #", "= test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples =", "= train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele validation_samples", "# salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels", "= preprocessing.Normalizer(norm = type) if scaler is not None: scaler.fit(train_data)", "# pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python')", "norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm", "scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea", "scaler = None if type == 'standard': scaler = preprocessing.StandardScaler()", "pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data", "convertim data frame-ul intr-un vector train_labels = train_labels[:,1] # pastram", "pentru citirea fisierelor from sklearn import preprocessing from sklearn import", "= pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels =", "engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar", "return train_data, test_data # Modelarea datelor vectorizer = TfidfVectorizer() training_features", "predictie pe datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation)))", "= train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels =", "validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels", "Modelarea datelor vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features =", "vectorizer = TfidfVectorizer() training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features", "sklearn import preprocessing from sklearn import svm # importarea modelului", "model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor in", "validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t',", "pd.read_csv('validation_samples.txt', sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1]", "vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation,", "model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification report: \")", "train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples", "= validation_samples.to_numpy() validation_samples = validation_samples[:,1] # salvam cuvintele validation_labels =", "modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test)", "== 'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1' or", "train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar cuvintele", "= pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy() label =", "# Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions} data_f", "= preprocessing.StandardScaler() elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif", "training_features = vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) #", "= scaler.transform(test_data) return scaled_train_data, scaled_test_data else: return train_data, test_data #", "validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train,", "procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele", "datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features,", "vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor", "test_predictions = model_svm.predict(norm_test) # predictie pe datele de test print(\"Classification", "test_samples.to_numpy() label = test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1]", "if type == 'standard': scaler = preprocessing.StandardScaler() elif type ==", "is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data)", "# Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _", "# functia care intoarce datele normalizate #tipul de normalizare este", "cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy()", "# Importarea librariilor import numpy as np import pandas as", "validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None,", "doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples =", "sep='\\t', header=None, engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul", "etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy()", "= type) if scaler is not None: scaler.fit(train_data) scaled_train_data =", "scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data =", "engine='python') train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector", "train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test) # predictie", "pandas pentru citirea fisierelor from sklearn import preprocessing from sklearn", "Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim", "from sklearn import preprocessing from sklearn import svm # importarea", "din text from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor", "= None if type == 'standard': scaler = preprocessing.StandardScaler() elif", "valori numerice din text from sklearn.metrics import classification_report, confusion_matrix #", "type='l2'): # functia care intoarce datele normalizate #tipul de normalizare", "from sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels =", "= preprocessing.MinMaxScaler() elif type == 'l1' or type == 'l2':", "testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test = normalize_data(training_features,", "svm # importarea modelului from sklearn.feature_extraction.text import TfidfVectorizer # modelarea", "-*- coding: utf-8 -*- \"\"\"Proiect.ipynb Automatically generated by Colaboratory. Original", "confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None, engine='python')", "etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples = test_samples.to_numpy()", "librariilor import numpy as np import pandas as pd #", "etichetele test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data, test_data,", "as np import pandas as pd # pandas pentru citirea", "= normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) # Aplicam", "train_labels = train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels", "SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train,", "import preprocessing from sklearn import svm # importarea modelului from", "scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data else:", "'l2': scaler = preprocessing.Normalizer(norm = type) if scaler is not", "= vectorizer.fit_transform(train_samples) validation_features = vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea", "vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test =", "norm_test = normalize_data(training_features, testing_features) norm_validation, _ = normalize_data(validation_features, validation_features) #", "invatare test_predictions = model_svm.predict(norm_test) # predictie pe datele de test", "Normalizarea datelor norm_train, norm_test = normalize_data(training_features, testing_features) norm_validation, _ =", "intr-un vector train_labels = train_labels[:,1] # pastram doar etichetele train_samples", "type == 'l1' or type == 'l2': scaler = preprocessing.Normalizer(norm", "generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1TR1Frf0EX4PtFZkLlVdGtMTINqhoQwRw \"\"\"", "l2 scaler = None if type == 'standard': scaler =", "pandas as pd # pandas pentru citirea fisierelor from sklearn", "model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions = model_svm.predict(norm_test) #", "pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t', header=None, engine='python') test_samples", "_ = normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm =", "pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels = validation_labels.to_numpy() validation_labels = validation_labels[:,1]", "print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea datelor", "scaled_test_data else: return train_data, test_data # Modelarea datelor vectorizer =", "sep='\\t', header=None, engine='python') validation_samples = validation_samples.to_numpy() validation_samples = validation_samples[:,1] #", "# definim modelul model_svm.fit(norm_train, train_labels) # procesul de invatare test_predictions", "print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation)))", "\") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) # Exportarea", "report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion matrix: \") print(confusion_matrix(validation_labels, model_svm.predict(norm_validation))) #", "classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t', header=None,", "validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt',", "de normalizare este setat implicit la l2 scaler = None", "= train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt', sep='\\t',", "salvam cuvintele validation_labels = pd.read_csv('validation_labels.txt', sep='\\t', header=None, engine='python') validation_labels =", "sklearn.metrics import classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt',", "normalize_data(validation_features, validation_features) # Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23,", "type == 'l2': scaler = preprocessing.Normalizer(norm = type) if scaler", "# modelarea datelor pentru a obtine valori numerice din text", "scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea datelor vectorizer", "# Aplicam modelul SVM model_svm = svm.SVC(kernel='linear', C=23, gamma=110) #", "svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) # procesul", "scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data = scaler.transform(test_data) return scaled_train_data, scaled_test_data", "'min_max': scaler = preprocessing.MinMaxScaler() elif type == 'l1' or type", "import classification_report, confusion_matrix # Incarcarea datelor train_labels = pd.read_csv('train_labels.txt', sep='\\t',", "engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] # pastram doar", "label = test_samples[:,0] # salvam etichetele test_samples = test_samples[:,1] #", "este setat implicit la l2 scaler = None if type", "care intoarce datele normalizate #tipul de normalizare este setat implicit", "if scaler is not None: scaler.fit(train_data) scaled_train_data = scaler.transform(train_data) scaled_test_data", "pe datele de test print(\"Classification report: \") print(classification_report(validation_labels, model_svm.predict(norm_validation))) print(\"Confusion", "Importarea librariilor import numpy as np import pandas as pd", "sep='\\t', header=None, engine='python') train_samples = train_samples.to_numpy() train_samples = train_samples[:,1] #", "import TfidfVectorizer # modelarea datelor pentru a obtine valori numerice", "salvam etichetele test_samples = test_samples[:,1] # salvam cuvintele def normalize_data(train_data,", "datele normalizate #tipul de normalizare este setat implicit la l2", "return scaled_train_data, scaled_test_data else: return train_data, test_data # Modelarea datelor", "= validation_labels[:,1] # pastram doar etichetele test_samples = pd.read_csv('test_samples.txt', sep='\\t',", "= validation_labels.to_numpy() validation_labels = validation_labels[:,1] # pastram doar etichetele test_samples", "= svm.SVC(kernel='linear', C=23, gamma=110) # definim modelul model_svm.fit(norm_train, train_labels) #", "Exportarea datelor in format CSV test_export = {'id':label,'label':test_predictions} data_f =", "preprocessing from sklearn import svm # importarea modelului from sklearn.feature_extraction.text", "= vectorizer.transform(validation_samples) testing_features = vectorizer.transform(test_samples) # Normalizarea datelor norm_train, norm_test", "TfidfVectorizer # modelarea datelor pentru a obtine valori numerice din", "train_labels.to_numpy() # convertim data frame-ul intr-un vector train_labels = train_labels[:,1]", "elif type == 'min_max': scaler = preprocessing.MinMaxScaler() elif type ==", "train_labels = train_labels[:,1] # pastram doar etichetele train_samples = pd.read_csv('train_samples.txt'," ]
[]
[ "function's signature, workflows need to run through the function itself", "track of workflow inputs that you've declared with add_workflow_input but", "def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]],", "None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED:", "Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received", "the provided inputs, if any input_kwargs = construct_input_promises([k for k", "is here only so that we don't have to re-evaluate.", "to its outputs. Basically this takes the place of propeller", "# Retrieve the entity from the node, and call it", "to streamline the pattern between workflows and tasks. Since tasks", "one task or other entity call at a time. This", "decorator. Please see notes on that object for additional information.", "# Even though the _local_execute call generally expects inputs to", "not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to", "element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in", "raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return", "the input to the task # binding_data.promise.var is the name", "{len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we should've already", "the functions above, which do additional checking. \"\"\" if len(self.compilation_state.nodes)", "NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from", "the above check, we just raise an Exception here. if", "k, v in kwargs.items(): if not isinstance(v, Promise): t =", "-> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\"", "some sanity checks # Even though the _local_execute call generally", "already been set. elif ( ctx.execution_state is not None and", "Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container", "objects should always point to the global start node. \"\"\"", "# we can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata,", "This is done to support the invariant that Workflow local", "# Recreate new promises that use the workflow's output names.", "as any other previous node. \"\"\" if not self.ready(): raise", "Promise]]) -> Promise: \"\"\" This is a helper function that", "ones that are Promises so let's filter for those. #", "tuple here, if it's a one element named tuple, then", "len(expected_output_names) == 1: # Here we have to handle the", "or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata,", "transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node", "\"\"\" entity_kwargs = {} for b in bindings: entity_kwargs[b.var] =", "workflow's tasks, whereas WorkflowMetadata represents metadata about the workflow itself.", "you want them to be used in the compilation. This", "entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] =", "else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names): raise", "len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) > 0: return", "output_tuple_name to understand that we're dealing with a one-element #", "all_input_values = get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise),", "map. Please see get_promise_map for the rest of the details.", "installation. This object will not initiate a network call to", "= self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as", "is starting a local workflow execution else: # Run some", "represents the defaults that are handed down to a workflow's", "tasks call execute from dispatch_execute which is in _local_execute, workflows", "Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name:", "-> Dict[str, Promise]: \"\"\" This holds the input promises to", "tracker map we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings,", "the given node output. \"\"\" if output_name in self._python_interface.outputs: raise", "FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if", "that, local execution notwithstanding, it is not evaluated again when", "node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf", "not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise],", "metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state =", "self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure", ") @property def compilation_state(self) -> CompilationState: \"\"\" Compilation is done", "is done node by node. This function will fill in", "if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently", "the two Workflow styles. For PythonFunctionWorkflows, the Python function is", "here only so that we don't have to re-evaluate. Or", "above check, we just raise an Exception here. if len(entity.python_interface.outputs)", "state. This loop adds Tasks that are defined within the", "a sub-workflow with a Python native value. for k, v", "== 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and", "p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\")", "always point to the global start node. \"\"\" return self._inputs", "return below from the output have to be pulled by", "state, which means * Has at least one node *", "asked to provide the expected interface. If at registration time", "the empty return case. # A workflow function may return", "returned. \"\"\" def __init__( self, project: str, domain: str, name:", "self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy]", "continue the execution context return self._local_execute(ctx, **input_kwargs) # Last is", "itself is # more or less stateless (the future-proofing get_all_tasks", "notwithstanding). However the # implementation of the TaskResolverMixin that this", "with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type,", "_local_execute -> execute From execute, different things happen for the", "python_interface=native_interface, ) @property def function(self): return self._workflow_function def task_name(self, t:", "binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names)", "list or dict of Promises, you must specify the python_type", "python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name}", "run once (again, this is with respect to the platform,", "task or other entity call at a time. This is", "should've already returned in the above check, we just raise", "intermediate_node_outputs[node] = {} # Retrieve the entity from the node,", "\"\"\" return self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes", "named to the one above. Please see the IDL for", "workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name =", "get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def", "tuple): raise AssertionError(\"The Workflow specification indicates multiple return values, received", "which do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return", "decorated function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param", "but haven't yet consumed. This # is an error that", "compilation. This mimics a 'closure' in the traditional sense of", "the inputs to the workflow. # _local_execute should've already ensured", "fill in the node's entity's input arguments, which are specified", "Arguments are supported for Workflow executions\") ctx = FlyteContextManager.current_context() #", "at serialization-time (aka compile-time). This is because while we can", "return at all # def wf(): # t1() # In", "checks # Even though the _local_execute call generally expects inputs", "def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] =", "function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically we need", "def nodes(self) -> List[Node]: return self._nodes def __repr__(self): return (", "inspect from dataclasses import dataclass from enum import Enum from", ") ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs =", "if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values that", "convention is used for naming outputs - and single-length-NamedTuples are", "there's only one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name", "self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} #", "assume that all nodes and workflow i/o changes were done", "tasks launched from this workflow are by default interruptible \"\"\"", "intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results)", "None # We are already in a local execution, just", "or results is None: continue # pragma: no cover #", "let the binding creation unwrap it and make a binding", "determine the entire structure of a task by looking at", "import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[],", "we need to repackage the promises coming from the tasks", "using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs,", "\"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults],", "the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var", "can be in launch plan only, but is here only", "pattern for Workflows is close to, but not exactly, the", "has already been set. elif ( ctx.execution_state is not None", "too for k, v in input_kwargs.items(): if k not in", "super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return", "PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer to a", "we force the user to declare entities already in a", "have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle", "a workflow that already exists on your Flyte installation. This", "raise Exception(f\"Workflow local execution expected 0 outputs but something received", ") return VoidPromise(self.name) # Because we should've already returned in", "workflow class has to keep track of its own compilation", "already been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type})", "FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure ==", "new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises,", "must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def", "from the tasks into Promises that match the workflow's #", "all inputs to that entity should've been already declared, we", "transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs, interface.outputs) return wrapper", "usage examples. :param _workflow_function: This argument is implicitly passed and", "workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults", "WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass", "IDL for more information but essentially, this WorkflowMetadataDefaults class represents", "not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition", "already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity,", "if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but", "f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute.", "x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises", "agruements and override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs", "self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type]", "in input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received unexpected", "Local execution of imperatively defined workflows is done node by", "return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals =", "with a one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding,", "AssertionError( f\"The Workflow specification indicates only one return value, received", "**kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is done to", "should be a tuple here, if it's a one element", "argument is implicitly passed and represents the decorated function. :param", "clean this up, maybe key off of the name instead", "an output with the given name from the given node", "are already in a local execution, just continue the execution", "isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to be", "isinstance(input_value, dict): input_promises = [] for _, v in input_value.items():", "Run some sanity checks # Even though the _local_execute call", "else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i]", "import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import", "\"\"\" def __init__( self, project: str, domain: str, name: str,", "to create an SdkWorkflow, except for the missing project and", "[Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class", "from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from flytekit.models", "i.e. the inputs to the workflow. # _local_execute should've already", "in the ones that are Promises so let's filter for", "it goes __call__ -> _local_execute -> execute From execute, different", "def execute(self, **kwargs): raise Exception(\"Should not be called\") def _local_execute(self,", "we don't have to re-evaluate. Or # we can re-evaluate.", "structure. It's also important to note that, local execution notwithstanding,", "from previously completed nodes and filling in the necessary inputs.", "compilation_state(self) -> CompilationState: \"\"\" Compilation is done a bit at", "the workflow itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible", "== BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k for", "self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str,", "interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults", "Whether or not tasks launched from this workflow are by", "binding_data.collection is not None: literals = [] for bd in", "handling of them is not a high priority # Again,", "str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow", "not evaluated again when the workflow runs on Flyte. That", "of a parent's workflow local run. # The context specifying", "Flyte # Literals. function_outputs = self.execute(**kwargs) # First handle the", "by extracting out the literals, and creating new Promises wf_outputs_as_literal_dict", "unbound inputs construct is just here to help workflow authors", "{self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}):", "which means there's another Promise-generating loop inside _local_execute too for", "type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type", "for the two Workflow styles. For PythonFunctionWorkflows, the Python function", "is run one at a time. \"\"\" if len(args) >", "in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for", "we have to handle the fact that the wf could've", "{output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx =", "\"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists", "self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through", "wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name]", "create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise", "why the user is asked to provide the expected interface.", "class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure !=", "Please see get_promise_map for the rest of the details. \"\"\"", "__call__ -> _local_execute -> execute From execute, different things happen", "== self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate", "The rest of this function looks like the above but", "= None ): \"\"\" Add an output with the given", "above function though will gather all the input # values", "a workflow's tasks, whereas WorkflowMetadata represents metadata about the workflow", "in workflow {self.name}\") if python_type is None: if type(p) ==", "of the task resolver change. The task resolver interface itself", "-> bool: \"\"\" This function returns whether or not the", "the task # binding_data.promise.var is the name of the upstream", "bound. \"\"\" # circular import from flytekit.core.node_creation import create_node ctx", "\" f\"Output bindings: {self._output_bindings} && \" ) def __call__(self, *args,", "can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface,", "= collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in self.python_interface.outputs.keys()]", "n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises", "what expresses the workflow structure. It's also important to note", "0 outputs but something received {result}\") if (1 < expected_outputs", "filled in only with the workflow inputs (if any). As", "of nodes to its outputs. Basically this takes the place", "@property def interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self)", "happen for the two Workflow styles. For PythonFunctionWorkflows, the Python", "if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The", "return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property", "user would return in mock function. That is, if it's", ") @property def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask)", "= list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None: continue", "stored in this map. After all nodes are run, we", "workflows and tasks. Since tasks call execute from dispatch_execute which", "= {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map", "we're doing it for the workflow as a whole rather", "sense of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters =", "respect to the platform, local runs notwithstanding). Please see the", "to declare entities already in a topological sort. To keep", "turn a binding into a Promise object, using a lookup", "Again use presence of output_tuple_name to understand that we're dealing", "also call an execute inside _local_execute. This makes mocking cleaner.", "return self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes def", ") -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is", "or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1:", "self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name =", "name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ):", "output of this will always be a combination of Python", ":param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether", "return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings])", "their outputs are stored in this map. After all nodes", "a map to start things off, filled in only with", "wf(): # t1() # In the former case we get", "returns whether or not the workflow is in a ready", "for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node,", "task by looking at the function's signature, workflows need to", "decorator declares a function to be a Flyte workflow. Workflows", "= translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new", "@property def python_interface(self) -> Interface: return self._python_interface @property def interface(self)", "workflows should not call non-Flyte entities since they are only", "\" ) def __call__(self, *args, **kwargs): \"\"\" The call pattern", "self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, )", "= [k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables)", "= self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t,", "# values but we're only interested in the ones that", "elif binding_data.map is not None: literals = {} for k,", "b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b)", "the execution context return self._local_execute(ctx, **input_kwargs) # Last is starting", "= transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node: return", "rest of this function looks like the above but now", "user is asked to provide the expected interface. If at", "be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs)", "( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, )", "Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution of", "import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import (", "# or it may not return at all # def", "# Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return", "return t1() # or it may not return at all", "Basically we need to repackage the promises coming from the", "outputs of the global input node, i.e. the inputs to", "a tuple, but return value is a tuple\" ) workflow_outputs", "like the above but now we're doing it for the", "len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for", "on your Flyte installation. This object will not initiate a", "a time, one task or other entity call at a", "this map. After all nodes are run, we fill in", "represents the decorated function. :param failure_policy: Use the options in", "of output_tuple_name to understand that we're dealing with a one-element", "def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ):", "workflow's # interface. We do that by extracting out the", "plan only, but is here only so that we don't", "upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is", "what the workflow would've returned had it been declared #", "input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was", "bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE", "= get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self,", "is None: if type(p) == list or type(p) == dict:", "SdkWorkflow, except for the missing project and domain self._nodes =", "from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from", "output bindings. # The return style here has to match", "flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver", "context specifying the local workflow execution has already been set.", "always end with an `else_()` clause\") t = self.python_interface.outputs[out] b", "Workflows are declarative entities that construct a DAG of tasks", "itself because the body of the function is what expresses", "str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ):", "if len(args) > 0: raise AssertionError(\"Only Keyword Arguments are supported", "LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput,", "match the workflow's # interface. We do that by extracting", "The first condition is compilation. if ctx.compilation_state is not None:", "Any, Callable, Dict, List, Optional, Tuple, Type, Union from flytekit.common", "entity must be bound. \"\"\" # circular import from flytekit.core.node_creation", "the workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name}", "1: raise AssertionError( f\"The Workflow specification indicates only one return", "for additional information. \"\"\" def __init__( self, workflow_function: Callable, metadata:", "return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface @property", "bound These conditions assume that all nodes and workflow i/o", "= None, interruptible: Optional[bool] = False, ): \"\"\" This decorator", "input promise bindings, but then override with the provided inputs,", "# more or less stateless (the future-proofing get_all_tasks function notwithstanding).", "reference_workflow( project: str, domain: str, name: str, version: str, )", "the workflow structure. It's also important to note that, local", "input_promises if isinstance(input_value, dict): input_promises = [] for _, v", "former case we get the task's VoidPromise, in the latter", "@property def compilation_state(self) -> CompilationState: \"\"\" Compilation is done a", "# and then fill them in using the node output", "combination of Python native values and Promises containing Flyte #", "the latter we get None if isinstance(function_outputs, VoidPromise) or function_outputs", "This # is an error that Admin would return at", "not None: literals = [] for bd in binding_data.collection.bindings: p", "Get default agruements and override with kwargs passed in input_kwargs", "entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you", "not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure =", "and domain self._nodes = all_nodes self._output_bindings = bindings if not", "class represents the defaults that are handed down to a", "0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)}", "word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes", "# keeps track of workflow inputs that you've declared with", "the values in kwargs are Promise objects for k, v", "Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\"", "from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from", "be pulled by fulfilling all of the # workflow's output", "be of the NodeOutput type {type(binding_data.promise)} found\" ) # b.var", "but should've been VoidPromise or None.\") # if there's only", "should've been already declared, we can just iterate through the", "AssertionError(\"The Workflow specification indicates multiple return values, received only one\")", "if _workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow):", "not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None:", "track of outputs, we create a map to start things", "in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises =", "as used. The above function though will gather all the", "notwithstanding, it is not evaluated again when the workflow runs", "List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name}", "in _local_execute, workflows should also call an execute inside _local_execute.", "anyways, but this allows flytekit to raise # the error", "serialization-time (aka compile-time). This is because while we can determine", "[] for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val)", "the call pattern for Tasks. For local execution, it goes", "start node. \"\"\" return self._inputs def __repr__(self): return super().__repr__() +", "that are handed down to a workflow's tasks, whereas WorkflowMetadata", "create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual outputs do", "input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises = [] for", "Because we should've already returned in the above check, we", "if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs)", "supported for Workflow executions\") ctx = FlyteContextManager.current_context() # Get default", "input arguments, which are specified using the bindings list, and", "we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) #", "we fill in workflow level outputs the same way as", "the place of propeller in resolving bindings, pulling in outputs", "at the function's signature, workflows need to run through the", "get_promise_map for the rest of the details. \"\"\" if binding_data.promise", "- {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs", "that all the values in kwargs are Promise objects for", "native values and Promises containing Flyte # Literals. function_outputs =", "This holds the input promises to the workflow. The nodes", "return values, received only one\") if len(output_names) != len(workflow_outputs): raise", "in the above check, we just raise an Exception here.", "{len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise", "not a high priority # Again, we're using the output_tuple_name", "named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a", "order and we shouldn't run into any dependency issues. That", "function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see", "the pattern between workflows and tasks. Since tasks call execute", "We do that by extracting out the literals, and creating", "again when the workflow runs on Flyte. That is, workflows", "class WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults:", "in Flyte. This Python object represents a workflow defined by", "**input_kwargs) # This condition is hit when this workflow (self)", "-> Dict[str, Promise]: \"\"\" Local execution of imperatively defined workflows", "class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a", "changes were done with the functions above, which do additional", "flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan", "less stateless (the future-proofing get_all_tasks function notwithstanding). However the #", ":std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This argument is", "0: return VoidPromise(self.name) # The values that we return below", "all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as part of", "AssertionError(\"A Conditional block (if-else) should always end with an `else_()`", "because the body of the function is what expresses the", "on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and", "WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults,", "by looking up the promises the node's bindings require, #", "loop. The reason is because we don't prevent users from", "node, and call it by looking up the promises the", "if (1 < expected_outputs == len(result)) or (result is not", "self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def", "self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs", "new promises that use the workflow's output names. new_promises =", "Admin would return at compile time anyways, but this allows", "the outputs of the global input node, i.e. the inputs", "Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if", "node's entity's input arguments, which are specified using the bindings", "global input node, i.e. the inputs to the workflow. #", "see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This", "this takes the place of propeller in resolving bindings, pulling", "the decorated function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy", "is in a ready state, which means * Has at", "been declared with a typing.NamedTuple of # length one. That", "was added as part of the task resolver change. The", "= workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs =", "the wf could've been declared with a typing.NamedTuple of #", "force the user to declare entities already in a topological", "to the global start node. \"\"\" return self._inputs def __repr__(self):", "return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\"", "= [] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises", "things off with the outputs of the global input node,", "is the name of the input to the task #", "self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for Workflow does", "only to try to streamline the pattern between workflows and", "Optional[bool] = False, ): \"\"\" This decorator declares a function", "The reason is because we don't prevent users from specifying", "compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def", "@property def nodes(self) -> List[Node]: return self._nodes def __repr__(self): return", "execute(self, **kwargs): raise Exception(\"Should not be called\") def _local_execute(self, ctx:", "self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added as part", "\"\"\" This holds the input promises to the workflow. The", "project: str, domain: str, name: str, version: str, inputs: Dict[str,", "node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results,", "run, for the ImperativeWorkflow, each node is run one at", "= workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface =", "the default input promise bindings, but then override with the", "self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified for wf", "helper function that will turn a binding into a Promise", "bindings = [] output_names = list(self.interface.outputs.keys()) # The reason the", "read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what workflows", "to, but not exactly, the call pattern for Tasks. For", "proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]}", "bindings. # The return style here has to match what", "create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from", "= {} # This unbound inputs construct is just here", "be a Flyte workflow. Workflows are declarative entities that construct", "Keyword Arguments are supported for Workflow executions\") ctx = FlyteContextManager.current_context()", "interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY)", "_ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We", "that construct a DAG of tasks using the data flow", "WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults", "Python native value. for k, v in kwargs.items(): if not", "kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output", "flytekit.loggers import logger from flytekit.models import interface as _interface_models from", "local workflow execution has already been set. elif ( ctx.execution_state", "do a one-element non-named tuple, # if it's a single", "v in kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k]", "in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity from", "import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not None:", "@property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self)", "{self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute. This function", ") if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for", ") -> Dict[str, Promise]: \"\"\" Local execution of imperatively defined", "and self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()] output_tuple", "i/o changes were done with the functions above, which do", "p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), )", "< expected_outputs == len(result)) or (result is not None and", "outputs from previously completed nodes and filling in the necessary", "\"\"\" Called by _local_execute. This function is how local execution", "== 1: # Again use presence of output_tuple_name to understand", "may not return at all # def wf(): # t1()", "!= len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx,", "input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every time an", "\"\"\" A reference workflow is a pointer to a workflow", ") # b.var is the name of the input to", "metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY", "return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property", "above check, we just raise an error here. if len(self.python_interface.outputs)", "Dict, List, Optional, Tuple, Type, Union from flytekit.common import constants", "FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the default", "the function body of a workflow is evaluated at serialization-time", "binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException(", "construct a DAG of tasks using the data flow between", "= get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise), all_input_values):", "just continue the execution context return self._local_execute(ctx, **input_kwargs) # Last", "workflow is in a ready state, which means * Has", "def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) ->", "0: raise FlyteValueException(results, f\"{results} received but should've been VoidPromise or", "executions\") ctx = FlyteContextManager.current_context() # Get default agruements and override", "self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()] output_tuple =", "> 0: raise AssertionError(\"Only Keyword Arguments are supported for Workflow", "in only with the workflow inputs (if any). As things", "the body of the workflow to the workflow # object", "This function returns whether or not the workflow is in", "k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate", "already in a local execution, just continue the execution context", "in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type:", "output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] =", "1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is", "# functionally, and 2) what a user would return in", "for a high-level understanding of what workflows are in Flyte.", "the function's signature, workflows need to run through the function", "initiate a network call to Admin, which is why the", "to be Promises, we don't have to do the #", "to the one above. Please see the IDL for more", "flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise,", "here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received", "== 0: if result is None or isinstance(result, VoidPromise): return", "self._local_execute(ctx, **input_kwargs) # Last is starting a local workflow execution", "the node, and call it by looking up the promises", "= all_nodes self._output_bindings = bindings if not output_names: return None", "get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) )", "the input # values but we're only interested in the", "b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs)", "get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str,", "the binding creation unwrap it and make a binding #", "= PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if", "compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface,", ") self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def", "raise AssertionError( \"Outputs specification for Workflow does not define a", "generally expects inputs to be Promises, we don't have to", "we don't have to do the # conversion here in", "Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n =", "Conditional block (if-else) should always end with an `else_()` clause\")", "style here has to match what 1) what the workflow", "are only run once (again, this is with respect to", "should've been VoidPromise or None.\") # if there's only one", "# The values that we return below from the output", "provided inputs, if any input_kwargs = construct_input_promises([k for k in", "f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name)", "= self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE,", "else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\"", "gather all the input # values but we're only interested", "the TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver) #", "Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\" Add an", "python_type type for {output_name}\" f\" starting with the container type", "Literals. function_outputs = self.execute(**kwargs) # First handle the empty return", "execution expected 0 outputs but something received {result}\") if (1", "Union[Tuple[Promise], Promise, VoidPromise]: # This is done to support the", "the function itself because the body of the function is", "all the input # values but we're only interested in", "any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs", "you've declared with add_workflow_input but haven't yet consumed. This #", "# Create a map that holds the outputs of each", "as comp_ctx: # Construct the default input promise bindings, but", "inside _local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def", "work with Promise objects # holding Flyte literal values. Even", "First handle the empty return case. # A workflow function", "= f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\" with", "or dict of Promises, you must specify the python_type type", "This class is similarly named to the one above. Please", "self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, )", "function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return", "the global start node. \"\"\" return self._inputs def __repr__(self): return", "override with the provided inputs, if any input_kwargs = construct_input_promises([k", "def python_interface(self) -> Interface: return self._python_interface @property def interface(self) ->", "ImperativeWorkflow, each node is run one at a time. \"\"\"", "= [] for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache)", "# This unbound inputs construct is just here to help", "to the workflow. # _local_execute should've already ensured that all", "# Every time an entity is added, mark it as", "if it's a single element then we return a single", "FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r in enumerate(results):", "* All workflow inputs are bound These conditions assume that", "version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference", "for Workflows is close to, but not exactly, the call", "workflow_outputs[i], t, ) bindings.append(b) # Save all the things necessary", "False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self):", "Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def", "failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): \"\"\"", "in mock function. That is, if it's a tuple, then", "if isinstance(results, VoidPromise) or results is None: continue # pragma:", "task that doesn't return anything # def wf(): # return", "no cover # Move along, nothing to assign # Because", "and we shouldn't run into any dependency issues. That is,", "to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name,", "NodeOutput type {type(binding_data.promise)} found\" ) # b.var is the name", "are Promises so let's filter for those. # There's probably", "A workflow function may return a task that doesn't return", "str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None", "1) what the workflow would've returned had it been declared", "self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property", "a time. This is why this workflow class has to", "body of a workflow is evaluated at serialization-time (aka compile-time).", "reference workflow is a pointer to a workflow that already", "pulling in outputs from previously completed nodes and filling in", "all nodes are run, we fill in workflow level outputs", "name(self) -> str: return self._name @property def short_name(self) -> str:", "class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer", "entities since they are only run once (again, this is", "self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def", "for imperative workflows runs. Because when an entity is added", "return n def add_workflow_input(self, input_name: str, python_type: Type) -> Interface:", "already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std(", "var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__(", "0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise", "upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE =", "class is similarly named to the one above. Please see", "wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase):", "set. elif ( ctx.execution_state is not None and ctx.execution_state.mode ==", "objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v #", "for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver ==", "inputs to that entity should've been already declared, we can", "between tasks. Unlike a task, the function body of a", "interruptible: bool def __post_init__(self): if self.interruptible is not True and", ") elif binding_data.map is not None: literals = {} for", "want them to be used in the compilation. This mimics", "specify the python_type type for {output_name}\" f\" starting with the", "workflow would've returned had it been declared # functionally, and", "= p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type", "isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) != 0:", "= 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class", "the missing project and domain self._nodes = all_nodes self._output_bindings =", "object represents a workflow defined by a function and decorated", "type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]]", "False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows`", "the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} #", "promise for a workflow call, when expecting a native value", "keep track of outputs, we create a map to start", "{} self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] =", "node output tracker map we have. entity = node.flyte_entity entity_kwargs", "input # values but we're only interested in the ones", "from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID,", "self.interruptible is not True and self.interruptible is not False: raise", "): \"\"\" Add an output with the given name from", "\"\"\" if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) >", "= False, ): \"\"\" This decorator declares a function to", "things off, filled in only with the workflow inputs (if", "run one at a time. \"\"\" if len(args) > 0:", "transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def", "version), inputs, outputs) def reference_workflow( project: str, domain: str, name:", "domain, name, version), inputs, outputs) def reference_workflow( project: str, domain:", "from the node, and call it by looking up the", "this allows flytekit to raise # the error earlier. self._unbound_inputs", "# First handle the empty return case. # A workflow", "function body of a workflow is evaluated at serialization-time (aka", "into any dependency issues. That is, we force the user", "the error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults,", "1: # Again use presence of output_tuple_name to understand that", "Again, we're using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name", "-> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version,", "annotations import collections import inspect from dataclasses import dataclass from", "context return self._local_execute(ctx, **input_kwargs) # Last is starting a local", "create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import", "len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out", "t, self.interface.inputs[k].type)) # The output of this will always be", "particularly troublesome but elegant handling of them is not a", "result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs ==", "import collections import inspect from dataclasses import dataclass from enum", "WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self):", "enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should", "override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) #", "containing Flyte # Literals. function_outputs = self.execute(**kwargs) # First handle", "bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]:", "coming from the tasks into Promises that match the workflow's", "one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results,", "isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n", "the things necessary to create an SdkWorkflow, except for the", "FlyteValueException(results, f\"{results} received but should've been VoidPromise or None.\") #", "The call pattern for Workflows is close to, but not", "received only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch", "have to re-evaluate. Or # we can re-evaluate. self._input_parameters =", "mock function. That is, if it's a tuple, then it", "new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, )", "value. for k, v in kwargs.items(): if not isinstance(v, Promise):", "None ): \"\"\" Add an output with the given name", "from dispatch_execute which is in _local_execute, workflows should also call", "wf(): # return t1() # or it may not return", "None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: #", "self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type: Type) ->", "): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if", "the container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring", "= Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum):", "of # length one. That convention is used for naming", "or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs =", "other entity call at a time. This is why this", "Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add", "# the error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata,", "out of it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple):", "promises that use the workflow's output names. new_promises = [Promise(var,", "change. The task resolver interface itself is # more or", "**input_kwargs) # Last is starting a local workflow execution else:", "output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names]", "if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs) > 0:", "[input_value] # Every time an entity is added, mark it", "self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map", "FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str,", "-> Node: \"\"\" Anytime you add an entity, all the", "something received {result}\") if (1 < expected_outputs == len(result)) or", "dispatch_execute which is in _local_execute, workflows should also call an", "self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we", "off with the outputs of the global input node, i.e.", "error will be returned. \"\"\" def __init__( self, project: str,", "self._inputs = {} # This unbound inputs construct is just", "_local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow(", "def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain,", "WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata =", "Python native values and Promises containing Flyte # Literals. function_outputs", "Callable, Dict, List, Optional, Tuple, Type, Union from flytekit.common import", "str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata", ") python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output", "interface as _interface_models from flytekit.models import literals as _literal_models from", "unwrap it and make a binding # collection/map out of", "import literals as _literal_models from flytekit.models.core import workflow as _workflow_model", ") as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs)", "a way to clean this up, maybe key off of", "how local execution for imperative workflows runs. Because when an", "str, python_type: Type) -> Interface: \"\"\" Adds an input to", "Since tasks call execute from dispatch_execute which is in _local_execute,", "failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or", "of what workflows are in Flyte. This Python object represents", "self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1", "raise an Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results,", "logger.debug(f\"Inferring python type for wf output {output_name} from Promise provided", "native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this -", "TypeEngine from flytekit.loggers import logger from flytekit.models import interface as", "wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference", "from dataclasses import dataclass from enum import Enum from typing", "FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface,", "do not match\") def execute(self, **kwargs): raise Exception(\"Should not be", "unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] )", "FlyteContextManager.current_context() # Get default agruements and override with kwargs passed", "means there's another Promise-generating loop inside _local_execute too for k,", "get_all_tasks function notwithstanding). However the # implementation of the TaskResolverMixin", "Use the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not", "@property def name(self) -> str: return self._name @property def short_name(self)", "We don't want to # iterate through the list here,", "isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple return values,", "to run through the function itself because the body of", "in outputs from previously completed nodes and filling in the", "raise FlyteValidationException(f\"Input {input_name} has already been specified for wf {self.name}.\")", "self._output_bindings = bindings if not output_names: return None if len(output_names)", "only, but is here only so that we don't have", "if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification for Workflow", "\"\"\" Adds an input to the workflow. \"\"\" if input_name", "that Admin would return at compile time anyways, but this", "# The first condition is compilation. if ctx.compilation_state is not", "= get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals))", "} def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise:", "import Any, Callable, Dict, List, Optional, Tuple, Type, Union from", "VoidPromise, in the latter we get None if isinstance(function_outputs, VoidPromise)", "functions above, which do additional checking. \"\"\" if len(self.compilation_state.nodes) ==", "If at registration time the interface provided causes an issue", "of the # workflow's output bindings. # The return style", "= {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] # Start", "of the name instead of value? all_input_values = get_input_values(kwargs) for", "ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name:", "flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from flytekit.models import", "python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name])", "List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\"", "it may not return at all # def wf(): #", "(get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element return get_promise(self.output_bindings[0].binding,", "**kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf,", "the interface provided causes an issue with compilation, an error", "that we're dealing with a one-element # named tuple if", "a topological sort. To keep track of outputs, we create", "had it been declared # functionally, and 2) what a", "\"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already", "run into any dependency issues. That is, we force the", "with the functions above, which do additional checking. \"\"\" if", "declared with a typing.NamedTuple of # length one. That convention", "Dict[str, Promise]: \"\"\" This holds the input promises to the", "raise AssertionError(\"A Conditional block (if-else) should always end with an", "WorkflowMetadataDefaults class represents the defaults that are handed down to", "dealing with a one-element # named tuple if self.python_interface.output_tuple_name: return", "of the function is what expresses the workflow structure. It's", "wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that use", "more information but essentially, this WorkflowMetadataDefaults class represents the defaults", "len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1:", "if self.python_interface and self.python_interface.output_tuple_name: variables = [k for k in", "loop inside _local_execute too for k, v in input_kwargs.items(): if", "what workflows are in Flyte. This Python object represents a", "found\" ) # b.var is the name of the input", "From execute, different things happen for the two Workflow styles.", "been declared # functionally, and 2) what a user would", "received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs", "time. \"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword Arguments", "if python_type is None: if type(p) == list or type(p)", "binding_data.map is not None: literals = {} for k, bd", "map of nodes to its outputs. Basically this takes the", "{expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map =", "as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value,", "a task, the function body of a workflow is evaluated", "As things are run, their outputs are stored in this", "function_outputs is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs,", "# The context specifying the local workflow execution has already", "workflows should also call an execute inside _local_execute. This makes", "see get_promise_map for the rest of the details. \"\"\" if", "what 1) what the workflow would've returned had it been", "( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface", "self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) ->", "it's a single element then we return a single element", "network call to Admin, which is why the user is", "self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property", "of the details. \"\"\" if binding_data.promise is not None: if", "an error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs,", "only so that we don't have to re-evaluate. Or #", "return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual outputs", "flytekit.models import literals as _literal_models from flytekit.models.core import workflow as", "{GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] # Start things", "# This condition is hit when this workflow (self) is", "with a Python native value. for k, v in kwargs.items():", "your Flyte installation. This object will not initiate a network", "with the workflow inputs (if any). As things are run,", "isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always end", "is currently {self}\") # Create a map that holds the", "str: return self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1]", "return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self)", "in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched from", "re-evaluate. Or # we can re-evaluate. self._input_parameters = None super().__init__(", "once (again, this is with respect to the platform, local", "None, interruptible: Optional[bool] = False, ): \"\"\" This decorator declares", "len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface", "nodes in these Promise objects should always point to the", "The reason the length 1 case is separate is because", "not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def", "= create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises =", "== dict: raise FlyteValidationException( f\"If specifying a list or dict", "a workflow is evaluated at serialization-time (aka compile-time). This is", "executions always work with Promise objects # holding Flyte literal", "else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results}", "# Iterate through the workflow outputs bindings = [] output_names", "logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the", "WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY", "a single element then we return a single element if", "filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value)", "priority # Again, we're using the output_tuple_name as a proxy.", "here, if it's a one element named tuple, then we", "not initiate a network call to Admin, which is why", "( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan", "condition is hit when this workflow (self) is being called", "that by extracting out the literals, and creating new Promises", "= transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if", "None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received", "def execute(self, **kwargs): \"\"\" Called by _local_execute. This function is", "str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A", "**kwargs): \"\"\" The call pattern for Workflows is close to,", "things are run, their outputs are stored in this map.", "results is None: continue # pragma: no cover # Move", "# Construct the default input promise bindings, but then override", "After all nodes are run, we fill in workflow level", "workflow's output bindings. # The return style here has to", "def add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\" Adds", "function. :param failure_policy: Use the options in flytekit.WorkflowFailurePolicy :param interruptible:", "def execute(self, **kwargs): \"\"\" This function is here only to", "we return below from the output have to be pulled", "through the list here, instead we should let the binding", "{expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _", "if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) !=", "return in mock function. That is, if it's a tuple,", "but not exactly, the call pattern for Tasks. For local", "if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables =", "'closure' in the traditional sense of the word. \"\"\" ctx", "isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else:", "added, mark it as used. The above function though will", "Python native values in the kwargs if you want them", "workflow local run. # The context specifying the local workflow", "in kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k]", "self.python_interface) raise ValueError(\"expected outputs and actual outputs do not match\")", "self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise,", "name of the input to the task # binding_data.promise.var is", "important to note that, local execution notwithstanding, it is not", "the invariant that Workflow local executions always work with Promise", "return self._inputs[input_name] def add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise],", "the tasks into Promises that match the workflow's # interface.", "task # binding_data.promise.var is the name of the upstream node's", "imperative workflows runs. Because when an entity is added using", "output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None:", "stateless (the future-proofing get_all_tasks function notwithstanding). However the # implementation", "be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs:", "same way as any other previous node. \"\"\" if not", "of its own compilation state. \"\"\" return self._compilation_state @property def", "\"\"\" Add an output with the given name from the", "= {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically", "ready state, which means * Has at least one node", "return self._local_execute(ctx, **input_kwargs) # Last is starting a local workflow", "a function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please", "tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal", "little loop was added as part of the task resolver", "call non-Flyte entities since they are only run once (again,", "self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name} && \"", "iterate through the nodes in order and we shouldn't run", "intermediate_node_outputs) # Handle the calling and outputs of each node's", "from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from", "= self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0:", "self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self,", "# Literals. function_outputs = self.execute(**kwargs) # First handle the empty", "This unbound inputs construct is just here to help workflow", "workflow inputs that you've declared with add_workflow_input but haven't yet", "import dataclass from enum import Enum from typing import Any,", "might be a list. We don't want to # iterate", "self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] =", "self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name))", "container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python", "the workflow to the workflow # object itself. for n", "python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set()", "as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import", "the one above. Please see the IDL for more information", "== len(result)) or (result is not None and expected_outputs ==", "ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k", "single element then we return a single element if len(self.output_bindings)", "PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine", "makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy:", "binding creation unwrap it and make a binding # collection/map", "def add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs)", "# interface. We do that by extracting out the literals,", "None: literals = [] for bd in binding_data.collection.bindings: p =", "def interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) ->", "execution context return self._local_execute(ctx, **input_kwargs) # Last is starting a", "doing it for the workflow as a whole rather #", "Tasks. For local execution, it goes __call__ -> _local_execute ->", "raise FlyteValidationException( f\"If specifying a list or dict of Promises,", "in a ready state, which means * Has at least", "= [] output_names = list(self.interface.outputs.keys()) # The reason the length", "f\"Output bindings: {self._output_bindings} && \" ) def __call__(self, *args, **kwargs):", "TODO do we need this - can this not be", "return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This function", "is hit when this workflow (self) is being called as", ") # Recreate new promises that use the workflow's output", "len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but should've been", "def reference_workflow( project: str, domain: str, name: str, version: str,", "error will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface", "values but we're only interested in the ones that are", "mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy]", "# def wf(): # return t1() # or it may", "intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity from the", "PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan:", "val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding],", "Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function", "# is an error that Admin would return at compile", "added as part of the task resolver change. The task", "dependency issues. That is, we force the user to declare", "Type) -> Interface: \"\"\" Adds an input to the workflow.", "the promises coming from the tasks into Promises that match", "in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object):", "self.add(n.flyte_entity) # Iterate through the workflow outputs bindings = []", "output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in", "be in launch plan only, but is here only so", "return tuple(bindings) def execute(self, **kwargs): \"\"\" This function is here", "in order and we shouldn't run into any dependency issues.", "__future__ import annotations import collections import inspect from dataclasses import", "is not evaluated again when the workflow runs on Flyte.", "from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager", "VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) != 0: raise", "= workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0],", "the name of the input to the task # binding_data.promise.var", "It's also important to note that, local execution notwithstanding, it", "List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes", "\"\"\" Local execution of imperatively defined workflows is done node", "results else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths", "in the traditional sense of the word. \"\"\" ctx =", "return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity:", "else: return None # We are already in a local", "== 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been", "itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible is not", "data flow between tasks. Unlike a task, the function body", "a parent's workflow local run. # The context specifying the", "case we get the task's VoidPromise, in the latter we", "if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple", "[] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self)", "but essentially, this WorkflowMetadataDefaults class represents the defaults that are", "self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def", "enumerate(function_outputs)} # Basically we need to repackage the promises coming", "set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs)", "Dict[str, Promise]] # Start things off with the outputs of", "dict: raise FlyteValidationException( f\"If specifying a list or dict of", "python_type is None: if type(p) == list or type(p) ==", "a binding # collection/map out of it. if len(output_names) ==", "Or # we can re-evaluate. self._input_parameters = None super().__init__( name=name,", "error that Admin would return at compile time anyways, but", "inputs that you've declared with add_workflow_input but haven't yet consumed.", "is done to support the invariant that Workflow local executions", "= {} # Retrieve the entity from the node, and", "= FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already", "TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise", "ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name:", "GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class", "return input_promises if isinstance(input_value, dict): input_promises = [] for _,", "are run, their outputs are stored in this map. After", "Please see the IDL for more information but essentially, this", "instead of value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda", "wf is currently {self}\") # Create a map that holds", "= bindings if not output_names: return None if len(output_names) ==", "details. \"\"\" if binding_data.promise is not None: if not isinstance(binding_data.promise,", "{self._output_bindings} && \" ) def __call__(self, *args, **kwargs): \"\"\" The", "we're dealing with a one-element # named tuple if self.python_interface.output_tuple_name:", "v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] #", "pattern between workflows and tasks. Since tasks call execute from", "for Workflow does not define a tuple, but return value", "we do a one-element non-named tuple, # if it's a", "(if-else) should always end with an `else_()` clause\") t =", "compile-time). This is because while we can determine the entire", "python_interface(self) -> Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface:", "output with the given name from the given node output.", "type for {output_name}\" f\" starting with the container type (e.g.", "list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None: continue #", "&& \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings}", "call, when expecting a native value for {k}\") with FlyteContextManager.with_context(", "decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on", "but now we're doing it for the workflow as a", "is not True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible", "name from the given node output. \"\"\" if output_name in", "def ready(self) -> bool: \"\"\" This function returns whether or", "the body of the function is what expresses the workflow", "Optional[Type] = None ): \"\"\" Add an output with the", "== list or type(p) == dict: raise FlyteValidationException( f\"If specifying", "_workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ):", "interruptible: Whether or not tasks launched from this workflow are", "# The rest of this function looks like the above", "function that will turn a binding into a Promise object,", "in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified for", "is in _local_execute, workflows should also call an execute inside", "= [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return create_task_output(new_promises, self.python_interface)", "len(args) > 0: raise AssertionError(\"Only Keyword Arguments are supported for", "flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException", "VoidPromise(self.name) # The values that we return below from the", "This loop adds Tasks that are defined within the body", "return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str,", "be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx,", "workflows are in Flyte. This Python object represents a workflow", "metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function)", "is, if it's a tuple, then it # should be", "to help workflow authors detect issues a bit earlier. It", "workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {}", "= False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults =", "= workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need", "self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return", "in using the node output tracker map we have. entity", "intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the nodes in", "sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self)", "entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__(", "if len(expected_output_names) == 1: # Here we have to handle", "at compile time anyways, but this allows flytekit to raise", "self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs,", "sort. To keep track of outputs, we create a map", ":std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what workflows are", "Promises so let's filter for those. # There's probably a", "always work with Promise objects # holding Flyte literal values.", "Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names):", "workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop was added", "just iterate through the nodes in order and we shouldn't", "in the node's entity's input arguments, which are specified using", "things happen for the two Workflow styles. For PythonFunctionWorkflows, the", "node * All workflow inputs are bound These conditions assume", "return None else: raise Exception(f\"Workflow local execution expected 0 outputs", "object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and", "the _local_execute call generally expects inputs to be Promises, we", "above, which do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0:", "v # Next iterate through the nodes in order. for", "WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure)", "map that holds the outputs of each node. intermediate_node_outputs =", "typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union", "being called as part of a parent's workflow local run.", "-> Union[Tuple[Promise], Promise, VoidPromise]: # This is done to support", "self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This function returns", "Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution", "be a list. We don't want to # iterate through", "= self.execute(**kwargs) # First handle the empty return case. #", "ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received", "FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", )", "FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p,", "(1 < expected_outputs == len(result)) or (result is not None", "dict of Promises, you must specify the python_type type for", "tasks. Since tasks call execute from dispatch_execute which is in", "is because while we can determine the entire structure of", "expresses the workflow structure. It's also important to note that,", "= [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return", "not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode ==", "[] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else:", "workflow. The nodes in these Promise objects should always point", "{expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} # Basically we", "node, i.e. the inputs to the workflow. # _local_execute should've", "out the literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals(", "self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs", "= 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class", "just raise an error here. if len(self.python_interface.outputs) == 0: raise", "since they are only run once (again, this is with", "bindings.append(b) # Save all the things necessary to create an", "# length one. That convention is used for naming outputs", "ready(self) -> bool: \"\"\" This function returns whether or not", "def __init__( self, project: str, domain: str, name: str, version:", "The context specifying the local workflow execution has already been", "a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The", "are Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] =", "task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs):", "The output of this will always be a combination of", "though will gather all the input # values but we're", "the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function: This argument", "we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return", "and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be boolean,", "of propeller in resolving bindings, pulling in outputs from previously", "# as direct scalars, which means there's another Promise-generating loop", "to be a Flyte workflow. Workflows are declarative entities that", "continue # pragma: no cover # Move along, nothing to", "= [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None", "f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \"", "def compilation_state(self) -> CompilationState: \"\"\" Compilation is done a bit", "if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]]", "[] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else", "we're using the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and", "and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs,", "**kwargs): \"\"\" Called by _local_execute. This function is how local", "with the outputs of the global input node, i.e. the", "that are defined within the body of the workflow to", "\"\"\" Compilation is done a bit at a time, one", "typing.NamedTuple of # length one. That convention is used for", "is similarly named to the one above. Please see the", "len(self.python_interface.outputs) if expected_outputs == 0: if result is None or", "FlyteValidationException( f\"Binding data Promises have to be of the NodeOutput", "promise bindings, but then override with the provided inputs, if", ") def __call__(self, *args, **kwargs): \"\"\" The call pattern for", "({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \" )", "comp_ctx: # Construct the default input promise bindings, but then", "type: Dict[Node, Dict[str, Promise]] # Start things off with the", "one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) #", "unexpected keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a", "binding # collection/map out of it. if len(output_names) == 1:", "*args, **kwargs): \"\"\" The call pattern for Workflows is close", "to the task # binding_data.promise.var is the name of the", "one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None:", "function to be a Flyte workflow. Workflows are declarative entities", "raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b", "own compilation state. \"\"\" return self._compilation_state @property def nodes(self) ->", "input_promises else: return [input_value] # Every time an entity is", "or (result is not None and expected_outputs == 1): return", "dataclass from enum import Enum from typing import Any, Callable,", "input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str,", "0: return False if len(self._unbound_inputs) > 0: return False return", "transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task,", "execution else: # Run some sanity checks # Even though", "we're only interested in the ones that are Promises so", "indicates only one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name", "a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs)", "at registration time the interface provided causes an issue with", "get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This", "self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property", "run, their outputs are stored in this map. After all", "task_resolver=self)) ) as comp_ctx: # Construct the default input promise", "is, workflows should not call non-Flyte entities since they are", "length one. That convention is used for naming outputs -", "inputs to be Promises, we don't have to do the", "b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b)", "This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None,", "the workflow as a whole rather # than just one", "at all # def wf(): # t1() # In the", "in launch plan only, but is here only so that", "_workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if", "a tuple, then it # should be a tuple here,", "{ input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs }", "implementation of the TaskResolverMixin that this workflow class inherits from", "in the necessary inputs. \"\"\" entity_kwargs = {} for b", "\"\"\" The call pattern for Workflows is close to, but", "all of the # workflow's output bindings. # The return", "the node output tracker map we have. entity = node.flyte_entity", "to the entity must be bound. \"\"\" # circular import", "bindings require, # and then fill them in using the", "from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise", "create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit when", "and Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs) #", "that are Promises so let's filter for those. # There's", "a single element if len(self.output_bindings) == 1: # Again use", "not None: literals = {} for k, bd in binding_data.map.bindings.items():", "ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs", "Save all the things necessary to create an SdkWorkflow, except", "return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node:", ") from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference", "{self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings:", "is with respect to the platform, local runs notwithstanding). Please", "super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow( project: str,", "# type: Dict[Node, Dict[str, Promise]] # Start things off with", "metadata about the workflow itself. \"\"\" interruptible: bool def __post_init__(self):", "the workflow. The nodes in these Promise objects should always", "inputs (if any). As things are run, their outputs are", "FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if python_type is", "only one return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is", "tuple(bindings) def execute(self, **kwargs): \"\"\" This function is here only", "from the given node output. \"\"\" if output_name in self._python_interface.outputs:", "specifying a list or dict of Promises, you must specify", "(the future-proofing get_all_tasks function notwithstanding). However the # implementation of", "name, version), inputs, outputs) def reference_workflow( project: str, domain: str,", "PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply", "Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) ->", "which is in _local_execute, workflows should also call an execute", "the entire structure of a task by looking at the", "Promise, VoidPromise]: # This is done to support the invariant", "return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is", "Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str:", "specification indicates only one return value, received {len(workflow_outputs)}\" ) if", "fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return", "name of the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var]", "a binding into a Promise object, using a lookup map.", "execution of imperatively defined workflows is done node by node.", "\"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword Arguments are", "the function is what expresses the workflow structure. It's also", "using the node output tracker map we have. entity =", "should always point to the global start node. \"\"\" return", "flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from flytekit.core.promise import", "as _interface_models from flytekit.models import literals as _literal_models from flytekit.models.core", "{} # Retrieve the entity from the node, and call", "used for naming outputs - and single-length-NamedTuples are # particularly", "or less stateless (the future-proofing get_all_tasks function notwithstanding). However the", "can this not be in launchplan only? # This can", "node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the", "def inputs(self) -> Dict[str, Promise]: \"\"\" This holds the input", "argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise for", "nodes and filling in the necessary inputs. \"\"\" entity_kwargs =", "declared # functionally, and 2) what a user would return", "for bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return", "in launchplan only? # This can be in launch plan", "is not None: literals = [] for bd in binding_data.collection.bindings:", "why this workflow class has to keep track of its", "it's a tuple, then it # should be a tuple", "execute from dispatch_execute which is in _local_execute, workflows should also", "ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type )", "workflow to the workflow # object itself. for n in", "the necessary inputs. \"\"\" entity_kwargs = {} for b in", "__init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface,", "though the _local_execute call generally expects inputs to be Promises,", "for a workflow call, when expecting a native value for", "= binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif", "binding_data.promise.var is the name of the upstream node's output we", "expecting a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION)", "map we have. entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs)", "sanity checks # Even though the _local_execute call generally expects", "a high priority # Again, we're using the output_tuple_name as", "workflow is evaluated at serialization-time (aka compile-time). This is because", "output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow", "entity = node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the", "in this loop. The reason is because we don't prevent", "len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for", "raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise): raise", "return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar))", "for node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node]", "entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs", "the # implementation of the TaskResolverMixin that this workflow class", "in a local execution, just continue the execution context return", "from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities,", "way to clean this up, maybe key off of the", "from flytekit.models import interface as _interface_models from flytekit.models import literals", "PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function:", "way as any other previous node. \"\"\" if not self.ready():", "in the kwargs if you want them to be used", ") raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache:", "function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in", "intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self,", "transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state", "input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every time", "is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode", "raise # the error earlier. self._unbound_inputs = set() super().__init__( name=name,", "promises the node's bindings require, # and then fill them", "then override with the provided inputs, if any input_kwargs =", "function. That is, if it's a tuple, then it #", "value is a tuple\" ) workflow_outputs = workflow_outputs[0] t =", "nodes in order and we shouldn't run into any dependency", "workflow is a pointer to a workflow that already exists", "if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k,", "self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is", "= TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not None:", "# if it's a single element then we return a", "workflow that already exists on your Flyte installation. This object", "workflow defined by a function and decorated with the :py:func:`@workflow", "This condition is hit when this workflow (self) is being", "all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self,", "{self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure", "for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict):", "for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx:", "Workflow does not define a tuple, but return value is", "latter we get None if isinstance(function_outputs, VoidPromise) or function_outputs is", "= construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs)", "call execute from dispatch_execute which is in _local_execute, workflows should", "name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) #", "wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)} #", "# particularly troublesome but elegant handling of them is not", "what a user would return in mock function. That is,", "Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This", "(again, this is with respect to the platform, local runs", "def short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) ->", "the workflow outputs bindings = [] output_names = list(self.interface.outputs.keys()) #", "self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") #", "it is not evaluated again when the workflow runs on", "= set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def", "of a workflow is evaluated at serialization-time (aka compile-time). This", "_common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask", "entire structure of a task by looking at the function's", "kwargs are Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k]", "the ImperativeWorkflow, each node is run one at a time.", "workflows need to run through the function itself because the", "intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan,", "declared with add_workflow_input but haven't yet consumed. This # is", "this not be in launchplan only? # This can be", "the name instead of value? all_input_values = get_input_values(kwargs) for input_value", "is the name of the upstream node's output we want", "Next iterate through the nodes in order. for node in", "== WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure = 1 return", "currently {self}\") # Create a map that holds the outputs", "the length 1 case is separate is because the one", "at a time. This is why this workflow class has", "in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v,", "Exception(f\"Workflow local execution expected 0 outputs but something received {result}\")", "there's another Promise-generating loop inside _local_execute too for k, v", "here in this loop. The reason is because we don't", "from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState,", "an error will be returned. \"\"\" def __init__( self, project:", "execution has already been set. elif ( ctx.execution_state is not", "topological sort. To keep track of outputs, we create a", "be Promises, we don't have to do the # conversion", "default input promise bindings, but then override with the provided", "None: raise AssertionError( \"Outputs specification for Workflow does not define", "to assign # Because we should've already returned in the", "is because the one output might be a list. We", "loop was added as part of the task resolver change.", "authors detect issues a bit earlier. It just # keeps", "-> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs)", "input_promises = [] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises", "There's probably a way to clean this up, maybe key", "with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value):", "the bindings list, and a map of nodes to its", "this WorkflowMetadataDefaults class represents the defaults that are handed down", "map to start things off, filled in only with the", "specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface =", "workflow runs on Flyte. That is, workflows should not call", "VoidPromise]: # This is done to support the invariant that", "for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A", "node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not", "should always end with an `else_()` clause\") t = self.python_interface.outputs[out]", "-> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]: return", "return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def", "from specifying inputs # as direct scalars, which means there's", "function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]:", "not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as", "the fact that the wf could've been declared with a", "you add an entity, all the inputs to the entity", "be a tuple here, if it's a one element named", "collections import inspect from dataclasses import dataclass from enum import", "else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: #", "# In the former case we get the task's VoidPromise,", "allows flytekit to raise # the error earlier. self._unbound_inputs =", "the output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple):", "looking up the promises the node's bindings require, # and", "values, received only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length", "to provide the expected interface. If at registration time the", "done with the functions above, which do additional checking. \"\"\"", "def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str:", "expected_outputs == len(result)) or (result is not None and expected_outputs", "import Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std,", "__post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE", "examples. :param _workflow_function: This argument is implicitly passed and represents", "# conversion here in this loop. The reason is because", "of the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif", "# Handle the calling and outputs of each node's entity", "this will always be a combination of Python native values", "the task's VoidPromise, in the latter we get None if", "def __post_init__(self): if self.interruptible is not True and self.interruptible is", "It just # keeps track of workflow inputs that you've", "!= 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has", "FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise or None.\"", "ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface", "so that we don't have to re-evaluate. Or # we", ") from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, )", "using the bindings list, and a map of nodes to", "if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else:", "if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but should've", "or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local execution", "outputs bindings = [] output_names = list(self.interface.outputs.keys()) # The reason", "or None.\") # if there's only one output, if len(expected_output_names)", "def compile(self, **kwargs): \"\"\" Supply static Python native values in", "not the workflow is in a ready state, which means", "runs on Flyte. That is, workflows should not call non-Flyte", "output_names = list(self.interface.outputs.keys()) # The reason the length 1 case", "\"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults =", "self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface", "workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx,", "to start things off, filled in only with the workflow", "need to repackage the promises coming from the tasks into", "the user is asked to provide the expected interface. If", "import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import", "outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self, name: str,", "empty return case. # A workflow function may return a", "not output_names: return None if len(output_names) == 1: return bindings[0]", "workflow are by default interruptible \"\"\" def wrapper(fn): workflow_metadata =", "policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY:", "name: str, version: str, inputs: Dict[str, Type], outputs: Dict[str, Type]", "if k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument", "raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r in", "return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\" This", "class inherits from (ClassStorageTaskResolver) # does store state. This loop", "tuple, but return value is a tuple\" ) workflow_outputs =", "_workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\"", "None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises", "could've been declared with a typing.NamedTuple of # length one.", "t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type))", "r # The rest of this function looks like the", "import Enum from typing import Any, Callable, Dict, List, Optional,", "nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str,", "= transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this - can", "self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\")", "that we don't have to re-evaluate. Or # we can", "an execute inside _local_execute. This makes mocking cleaner. \"\"\" return", "values. Even in a wf, a user can call a", "inputs # as direct scalars, which means there's another Promise-generating", "return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\"", "to a workflow that already exists on your Flyte installation.", "child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs", "starting a local workflow execution else: # Run some sanity", "multiple return values, received only one\") if len(output_names) != len(workflow_outputs):", "t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs,", "for Tasks. For local execution, it goes __call__ -> _local_execute", "None else: raise Exception(f\"Workflow local execution expected 0 outputs but", "get None if isinstance(function_outputs, VoidPromise) or function_outputs is None: if", "Node from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node,", "its outputs. Basically this takes the place of propeller in", "t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i],", "{self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] =", "# t1() # In the former case we get the", "wf could've been declared with a typing.NamedTuple of # length", "mark it as used. The above function though will gather", "called as part of a parent's workflow local run. #", "to support the invariant that Workflow local executions always work", "local execution notwithstanding, it is not evaluated again when the", "Called by _local_execute. This function is how local execution for", "error earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(),", "of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx,", "outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\" Local", "tuple, then we do a one-element non-named tuple, # if", "want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\",", "the local workflow execution has already been set. elif (", "execution for imperative workflows runs. Because when an entity is", "**kwargs) -> Node: \"\"\" Anytime you add an entity, all", "exists on your Flyte installation. This object will not initiate", "# The output of this will always be a combination", "the above but now we're doing it for the workflow", "# The reason the length 1 case is separate is", "{self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow", "[None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None", "with the container type (e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var]", "a bit at a time, one task or other entity", "for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs", "returned had it been declared # functionally, and 2) what", "Please see notes on that object for additional information. \"\"\"", "**kwargs): \"\"\" Supply static Python native values in the kwargs", "part of the task resolver change. The task resolver interface", "local workflow execution else: # Run some sanity checks #", "function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\", ) return", "normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for", "with compilation, an error will be returned. \"\"\" def __init__(", "handle the empty return case. # A workflow function may", "traditional sense of the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters", "notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param", "that we return below from the output have to be", "2) what a user would return in mock function. That", "def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self) ->", "as ctx: b = binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type", "literals as _literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE", "task's VoidPromise, in the latter we get None if isinstance(function_outputs,", "return value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise", "different things happen for the two Workflow styles. For PythonFunctionWorkflows,", "Has at least one node * All workflow inputs are", "input_kwargs.update(kwargs) # The first condition is compilation. if ctx.compilation_state is", "= binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) #", "to re-evaluate. Or # we can re-evaluate. self._input_parameters = None", "function is what expresses the workflow structure. It's also important", "len(result)) or (result is not None and expected_outputs == 1):", "evaluated again when the workflow runs on Flyte. That is,", "returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return", "of each node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys())", "only interested in the ones that are Promises so let's", "tasks into Promises that match the workflow's # interface. We", "PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from", "direct scalars, which means there's another Promise-generating loop inside _local_execute", "clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out, self.interface.outputs[out].type,", "the python_type type for {output_name}\" f\" starting with the container", "True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for", "reason is because we don't prevent users from specifying inputs", "order. for node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys():", "import logger from flytekit.models import interface as _interface_models from flytekit.models", "raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def to_flyte_model(self): if self.on_failure", "FlyteValidationException( f\"If specifying a list or dict of Promises, you", "close to, but not exactly, the call pattern for Tasks.", "resolver change. The task resolver interface itself is # more", "outputs do not match\") def execute(self, **kwargs): raise Exception(\"Should not", "== 1: return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\"", "a map that holds the outputs of each node. intermediate_node_outputs", "outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise", "import inspect from dataclasses import dataclass from enum import Enum", "creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs,", "translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity,", "a local execution, just continue the execution context return self._local_execute(ctx,", "Promise]: \"\"\" This holds the input promises to the workflow.", "**kwargs) def ready(self) -> bool: \"\"\" This function returns whether", "don't want to # iterate through the list here, instead", "run. # The context specifying the local workflow execution has", "for {output_name}\" f\" starting with the container type (e.g. List[int]\"", "\"Outputs specification for Workflow does not define a tuple, but", "transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node", "do the # conversion here in this loop. The reason", "!= 1: raise AssertionError( f\"The Workflow specification indicates only one", "__init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name", "this - can this not be in launchplan only? #", "constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from flytekit.core.base_task", "declare entities already in a topological sort. To keep track", "let's filter for those. # There's probably a way to", "import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state", "but should've been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys())", "# Again use presence of output_tuple_name to understand that we're", "Promise objects should always point to the global start node.", "from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException,", "binding into a Promise object, using a lookup map. Please", "for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next", "This function will fill in the node's entity's input arguments,", "results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or", "workflow {self.name}\") if python_type is None: if type(p) == list", ") bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple):", "WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn,", "see the IDL for more information but essentially, this WorkflowMetadataDefaults", "propeller in resolving bindings, pulling in outputs from previously completed", "in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]])", "[k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones", "don't have to do the # conversion here in this", "between workflows and tasks. Since tasks call execute from dispatch_execute", "**input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if result", "_workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name))", "as child_ctx: result = self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if", "hit when this workflow (self) is being called as part", "entity, all the inputs to the entity must be bound.", "Anytime you add an entity, all the inputs to the", "if len(output_names) == 1: return bindings[0] return tuple(bindings) def execute(self,", "= {} for k, bd in binding_data.map.bindings.items(): p = get_promise(bd,", "List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ): \"\"\" Add", "the global input node, i.e. the inputs to the workflow.", "input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation.", "a workflow call, when expecting a native value for {k}\")", "given name from the given node output. \"\"\" if output_name", "if it's a tuple, then it # should be a", "wf_outputs_as_map = {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for", "to Admin, which is why the user is asked to", "the word. \"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface)", "a lookup map. Please see get_promise_map for the rest of", "workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has", "keyword argument {k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise", "ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx, **input_kwargs)", "tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs}", "already declared, we can just iterate through the nodes in", "# implementation of the TaskResolverMixin that this workflow class inherits", "pointer to a workflow that already exists on your Flyte", "but something received {result}\") if (1 < expected_outputs == len(result))", "logger from flytekit.models import interface as _interface_models from flytekit.models import", "# iterate through the list here, instead we should let", "presence of output_tuple_name to understand that we're dealing with a", "time. This is why this workflow class has to keep", "(result is not None and expected_outputs == 1): return create_native_named_tuple(ctx,", "declared, we can just iterate through the nodes in order", "input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been specified", "in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little", "from typing import Any, Callable, Dict, List, Optional, Tuple, Type,", "is not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\")", "workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance =", "scalars, which means there's another Promise-generating loop inside _local_execute too", "PythonFunctionWorkflows, the Python function is run, for the ImperativeWorkflow, each", "== 0: return False if len(self._unbound_inputs) > 0: return False", "): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function))", "workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False,", "== 0: return VoidPromise(self.name) # The values that we return", "the nodes in order and we shouldn't run into any", "for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones =", "intermediate_node_outputs),) # Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs)", "for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None #", "an entity is added, mark it as used. The above", "runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples.", "that holds the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE:", "this is with respect to the platform, local runs notwithstanding).", "= WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow(", "raise ValueError(f\"Received a promise for a workflow call, when expecting", "this workflow class has to keep track of its own", "output might be a list. We don't want to #", "k, v in input_kwargs.items(): if k not in self.interface.inputs: raise", "= Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self,", "here, instead we should let the binding creation unwrap it", "define a tuple, but return value is a tuple\" )", "holding Flyte literal values. Even in a wf, a user", "use presence of output_tuple_name to understand that we're dealing with", "> 0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\"", "while we can determine the entire structure of a task", "-> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a", "_interface_models from flytekit.models import literals as _literal_models from flytekit.models.core import", "wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]: function_outputs} else:", "entity_kwargs class WorkflowBase(object): def __init__( self, name: str, workflow_metadata: WorkflowMetadata,", "the workflow would've returned had it been declared # functionally,", "are in Flyte. This Python object represents a workflow defined", "is an error that Admin would return at compile time", "node is run one at a time. \"\"\" if len(args)", "f\"{function_outputs} received but should've been VoidPromise or None.\" ) expected_output_names", "only with the workflow inputs (if any). As things are", "help workflow authors detect issues a bit earlier. It just", "will not initiate a network call to Admin, which is", "literals[k] = p.val return Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding", "bindings, pulling in outputs from previously completed nodes and filling", "v in input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received", "Promise]] ) -> Dict[str, Promise]: \"\"\" Local execution of imperatively", "these Promise objects should always point to the global start", "the upstream node's output we want return outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar", "workflow execution else: # Run some sanity checks # Even", "project: str, domain: str, name: str, version: str, ) ->", "call it by looking up the promises the node's bindings", "objects # holding Flyte literal values. Even in a wf,", "FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't already be", "entity is added, mark it as used. The above function", "elif ( ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION", "self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1: if", "run through the function itself because the body of the", "ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) >", "len(self.output_bindings) == 1: # Again use presence of output_tuple_name to", "ready, wf is currently {self}\") # Create a map that", "Create a map that holds the outputs of each node.", "Dict[str, Promise]]) -> Promise: \"\"\" This is a helper function", "node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]]", "the workflow. # _local_execute should've already ensured that all the", "make a binding # collection/map out of it. if len(output_names)", "= {} self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]]", "# than just one node at a time. if len(self.python_interface.outputs)", "a one element named tuple, then we do a one-element", "of Python native values and Promises containing Flyte # Literals.", "list here, instead we should let the binding creation unwrap", "FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from", "rather # than just one node at a time. if", "in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\",", "completed nodes and filling in the necessary inputs. \"\"\" entity_kwargs", "outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type:", "that entity should've been already declared, we can just iterate", "match what 1) what the workflow would've returned had it", "probably a way to clean this up, maybe key off", "troublesome but elegant handling of them is not a high", "default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface", "that the wf could've been declared with a typing.NamedTuple of", "function may return a task that doesn't return anything #", "Every time an entity is added, mark it as used.", "can determine the entire structure of a task by looking", "This mimics a 'closure' in the traditional sense of the", "Union from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user import", "if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve", "additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False if", "declares a function to be a Flyte workflow. Workflows are", "return self._nodes def __repr__(self): return ( f\"WorkflowBase - {self._name} &&", "self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The", "= list(self.interface.outputs.keys()) # The reason the length 1 case is", "resolving bindings, pulling in outputs from previously completed nodes and", "as _literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE =", "list or type(p) == dict: raise FlyteValidationException( f\"If specifying a", "This is a helper function that will turn a binding", "List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf", "if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving", "and make a binding # collection/map out of it. if", "elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection", "len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\") for idx, r", "ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is", "and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results", "__repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs):", "flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine", "isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map = {expected_output_names[0]:", "entity's input arguments, which are specified using the bindings list,", "def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs)", "Basically this takes the place of propeller in resolving bindings,", "return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None:", "expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs", "actual outputs do not match\") def execute(self, **kwargs): raise Exception(\"Should", "the kwargs if you want them to be used in", "local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage", "with a typing.NamedTuple of # length one. That convention is", "# _local_execute should've already ensured that all the values in", "The nodes in these Promise objects should always point to", "then we return a single element if len(self.output_bindings) == 1:", "values that we return below from the output have to", "= FlyteContextManager.current_context() # Get default agruements and override with kwargs", "all the things necessary to create an SdkWorkflow, except for", "VoidPromise or None.\") # if there's only one output, if", "for more information but essentially, this WorkflowMetadataDefaults class represents the", "Promises have to be of the NodeOutput type {type(binding_data.promise)} found\"", "This is why this workflow class has to keep track", "get the task's VoidPromise, in the latter we get None", "f\"The Workflow specification indicates only one return value, received {len(workflow_outputs)}\"", "that doesn't return anything # def wf(): # return t1()", "len(output_names) == 1: return bindings[0] return tuple(bindings) def execute(self, **kwargs):", "are handed down to a workflow's tasks, whereas WorkflowMetadata represents", "that Workflow local executions always work with Promise objects #", "None and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise", "= WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This", "cover # Move along, nothing to assign # Because we", "must specify the python_type type for {output_name}\" f\" starting with", "WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure", "False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible)", "in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF", "is not a high priority # Again, we're using the", "FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This is done", "interface. We do that by extracting out the literals, and", "Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def get_promise(binding_data:", "p = get_promise(bd, outputs_cache) literals[k] = p.val return Promise( var=\"placeholder\",", "if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure =", "body of the workflow to the workflow # object itself.", "WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return", "of Promises, you must specify the python_type type for {output_name}\"", "Workflow specification indicates only one return value, received {len(workflow_outputs)}\" )", "Promise( var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map(", "don't prevent users from specifying inputs # as direct scalars,", "False, ): \"\"\" This decorator declares a function to be", "import TypeEngine from flytekit.loggers import logger from flytekit.models import interface", "self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface @property def", "we get the task's VoidPromise, in the latter we get", "+ f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by", "time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values", "raise FlyteValidationException( f\"Binding data Promises have to be of the", "WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs", "input to the task # binding_data.promise.var is the name of", "it by looking up the promises the node's bindings require,", "self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task:", "should also call an execute inside _local_execute. This makes mocking", "def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) ->", "down to a workflow's tasks, whereas WorkflowMetadata represents metadata about", "run, we fill in workflow level outputs the same way", "= self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t,", "Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs,", "for the rest of the details. \"\"\" if binding_data.promise is", "that match the workflow's # interface. We do that by", "-> List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase -", "to repackage the promises coming from the tasks into Promises", "return VoidPromise(self.name) # The values that we return below from", "Flyte. That is, workflows should not call non-Flyte entities since", "data Promises have to be of the NodeOutput type {type(binding_data.promise)}", "1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected outputs and actual", "dataclasses import dataclass from enum import Enum from typing import", "the defaults that are handed down to a workflow's tasks,", "with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result =", "of workflow inputs that you've declared with add_workflow_input but haven't", "if len(self.output_bindings) == 1: # Again use presence of output_tuple_name", "of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node,", "function though will gather all the input # values but", "to the platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py`", "None: if type(p) == list or type(p) == dict: raise", "end with an `else_()` clause\") t = self.python_interface.outputs[out] b =", "be a combination of Python native values and Promises containing", "map. After all nodes are run, we fill in workflow", "with respect to the platform, local runs notwithstanding). Please see", "interface. If at registration time the interface provided causes an", "as direct scalars, which means there's another Promise-generating loop inside", "does not define a tuple, but return value is a", "= v # Next iterate through the nodes in order.", "it as used. The above function though will gather all", "execute(self, **kwargs): \"\"\" This function is here only to try", "if any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs)", "== 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise", "interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we", "**kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan,", "entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise)", "naming outputs - and single-length-NamedTuples are # particularly troublesome but", "= results else: if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different", "additional information. \"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata],", "through the workflow outputs bindings = [] output_names = list(self.interface.outputs.keys())", "expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if result is", "a DAG of tasks using the data flow between tasks.", "if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification indicates", "the literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx,", "inputs are bound These conditions assume that all nodes and", "None, interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or", "be used in the compilation. This mimics a 'closure' in", "the workflow # object itself. for n in comp_ctx.compilation_state.nodes: if", "notes on that object for additional information. \"\"\" def __init__(", "raise ValueError(\"expected outputs and actual outputs do not match\") def", "in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self,", "has to keep track of its own compilation state. \"\"\"", "been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names)", "Flyte workflow. Workflows are declarative entities that construct a DAG", "call generally expects inputs to be Promises, we don't have", "ensured that all the values in kwargs are Promise objects", "we don't prevent users from specifying inputs # as direct", "for input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value", "for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return", "iterate through the list here, instead we should let the", "single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding, intermediate_node_outputs) for b", "val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals = [] for", "flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import", "for Workflow executions\") ctx = FlyteContextManager.current_context() # Get default agruements", "get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for x in", "the IDL for more information but essentially, this WorkflowMetadataDefaults class", "flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState,", "elif binding_data.collection is not None: literals = [] for bd", "that already exists on your Flyte installation. This object will", "self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _", "launchplan only? # This can be in launch plan only,", "the rest of the details. \"\"\" if binding_data.promise is not", "in a topological sort. To keep track of outputs, we", "interface=self.python_interface, **input_kwargs) # This condition is hit when this workflow", "assign # Because we should've already returned in the above", "takes the place of propeller in resolving bindings, pulling in", "this function looks like the above but now we're doing", "domain: str, name: str, version: str, inputs: Dict[str, Type], outputs:", "and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not", "an `else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx,", "are specified using the bindings list, and a map of", "List[_literal_models.Binding], outputs_cache: Dict[Node, Dict[str, Promise]] ) -> Dict[str, Promise]: \"\"\"", "through the nodes in order and we shouldn't run into", "should not call non-Flyte entities since they are only run", "to clean this up, maybe key off of the name", "of this will always be a combination of Python native", "\"\"\" interruptible: bool def __post_init__(self): if self.interruptible is not True", "understand that we're dealing with a one-element # named tuple", "flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that use the", "itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver", "error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs}", "not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if", "do that by extracting out the literals, and creating new", "import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection", "Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals", "entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is", "self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name,", "if type(p) == list or type(p) == dict: raise FlyteValidationException(", "None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx:", "output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings @property def nodes(self) -> List[Node]:", "local execution expected 0 outputs but something received {result}\") if", "expected_outputs == 0: if result is None or isinstance(result, VoidPromise):", "workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\"", "= ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def", "an entity is added using the add_entity function, all inputs", "within the body of the workflow to the workflow #", "_workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, )", "a one-element # named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),)", "understanding of what workflows are in Flyte. This Python object", "the Python function is run, for the ImperativeWorkflow, each node", "launched from this workflow are by default interruptible \"\"\" def", "haven't yet consumed. This # is an error that Admin", "_local_execute. This function is how local execution for imperative workflows", "outputs_cache[binding_data.promise.node][binding_data.promise.var] elif binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif", "a map of nodes to its outputs. Basically this takes", "flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output,", "expects inputs to be Promises, we don't have to do", "function looks like the above but now we're doing it", "nodes and workflow i/o changes were done with the functions", "by node. This function will fill in the node's entity's", "0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object):", "from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition", "the data flow between tasks. Unlike a task, the function", "construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes)", "is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not", "a function to be a Flyte workflow. Workflows are declarative", "of it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if", "k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This", "self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface", "off, filled in only with the workflow inputs (if any).", "import FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import", "the ones that are Promises so let's filter for those.", "call pattern for Workflows is close to, but not exactly,", "have to be pulled by fulfilling all of the #", "TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver) # does", "var=input_name)) for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache:", "FlyteValidationException, FlyteValueException from flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver", "WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to the one", "= get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif", "if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single", "for the workflow as a whole rather # than just", "native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) )", "creation unwrap it and make a binding # collection/map out", "return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible:", "self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs", "get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def __init__( self, name:", "expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface", "None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx:", "specification for Workflow does not define a tuple, but return", "_local_execute call generally expects inputs to be Promises, we don't", "function, all inputs to that entity should've been already declared,", "out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block", "when expecting a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state(", "str, domain: str, name: str, version: str, ) -> Callable[[Callable[...,", "= get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs of", "similarly named to the one above. Please see the IDL", "but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because", "note that, local execution notwithstanding, it is not evaluated again", "-> List[Node]: return self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]:", "default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY)", "raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings: List[_literal_models.Binding], outputs_cache: Dict[Node,", "add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def", "ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding", "Callable, metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function", "here to help workflow authors detect issues a bit earlier.", "not None and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface)", "# pragma: no cover # Move along, nothing to assign", "isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow", "self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We are already", "flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is not", "we need this - can this not be in launchplan", "isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v,", "binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)),", "if len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but", "causes an issue with compilation, an error will be returned.", "= f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO", "also important to note that, local execution notwithstanding, it is", "return anything # def wf(): # return t1() # or", "Promises that match the workflow's # interface. We do that", "Start things off with the outputs of the global input", "nones = [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else:", "been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface", "time an entity is added, mark it as used. The", "_workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named", "a typing.NamedTuple of # length one. That convention is used", "binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface =", "been VoidPromise or None.\") # if there's only one output,", "_literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is", "the user to declare entities already in a topological sort.", "node. This function will fill in the node's entity's input", "( ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ):", "would've returned had it been declared # functionally, and 2)", "FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class", "will turn a binding into a Promise object, using a", "to the workflow. \"\"\" if input_name in self._inputs: raise FlyteValidationException(f\"Input", "doesn't return anything # def wf(): # return t1() #", "native values in the kwargs if you want them to", "Promise objects # holding Flyte literal values. Even in a", "single element if len(self.output_bindings) == 1: # Again use presence", "WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure}", "first condition is compilation. if ctx.compilation_state is not None: return", "workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in", "about the workflow itself. \"\"\" interruptible: bool def __post_init__(self): if", "are # particularly troublesome but elegant handling of them is", "&& \" ) def __call__(self, *args, **kwargs): \"\"\" The call", "this up, maybe key off of the name instead of", "b = binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b)", "self, project: str, domain: str, name: str, version: str, inputs:", "Flyte. This Python object represents a workflow defined by a", "it been declared # functionally, and 2) what a user", "self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool]", "expected interface. If at registration time the interface provided causes", "default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else:", "all the inputs to the entity must be bound. \"\"\"", "any other previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow", "time anyways, but this allows flytekit to raise # the", "t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface =", "ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager,", "is, we force the user to declare entities already in", "interface(self) -> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]:", "Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def", "one-element non-named tuple, # if it's a single element then", "exists in workflow {self.name}\") if python_type is None: if type(p)", "workflow (self) is being called as part of a parent's", "input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value, dict): input_promises = []", "inputs construct is just here to help workflow authors detect", "create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy:", "one element named tuple, then we do a one-element non-named", "by fulfilling all of the # workflow's output bindings. #", "workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata", "to do the # conversion here in this loop. The", "the details. \"\"\" if binding_data.promise is not None: if not", "should let the binding creation unwrap it and make a", "a task by looking at the function's signature, workflows need", "&& \" f\"Output bindings: {self._output_bindings} && \" ) def __call__(self,", "issues. That is, we force the user to declare entities", "non-named tuple, # if it's a single element then we", "i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional", ") @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if (", "Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a pointer", "is why this workflow class has to keep track of", "= node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling", "on Flyte. That is, workflows should not call non-Flyte entities", "will be returned. \"\"\" def __init__( self, project: str, domain:", "= CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs construct", "is None: continue # pragma: no cover # Move along,", "value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as", "@dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self): if ( self.on_failure", "if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]]", "the entity from the node, and call it by looking", "in these Promise objects should always point to the global", "input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def", "{len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i],", "the add_entity function, all inputs to that entity should've been", "element if len(self.output_bindings) == 1: # Again use presence of", "A reference workflow is a pointer to a workflow that", "call at a time. This is why this workflow class", "execute From execute, different things happen for the two Workflow", "not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data", "is compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self,", "in the compilation. This mimics a 'closure' in the traditional", "prevent users from specifying inputs # as direct scalars, which", "return at compile time anyways, but this allows flytekit to", "Promise]], python_type: Optional[Type] = None ): \"\"\" Add an output", "python_type: Type) -> Interface: \"\"\" Adds an input to the", "LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf:", "tasks. Unlike a task, the function body of a workflow", "intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names): raise FlyteValueException(results,", "domain self._nodes = all_nodes self._output_bindings = bindings if not output_names:", "and expected_outputs == 1): return create_native_named_tuple(ctx, result, self.python_interface) raise ValueError(\"expected", "than just one node at a time. if len(self.python_interface.outputs) ==", "you must specify the python_type type for {output_name}\" f\" starting", "raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if python_type", "bool def __post_init__(self): if self.interruptible is not True and self.interruptible", "= self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation. if", "VoidPromise) or results is None: continue # pragma: no cover", "if there's only one output, if len(expected_output_names) == 1: if", "def name(self) -> str: return self._name @property def short_name(self) ->", "defined within the body of the workflow to the workflow", "Workflow specification indicates multiple return values, received only one\") if", "not call non-Flyte entities since they are only run once", "that use the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var])", "Promise): raise ValueError(f\"Received a promise for a workflow call, when", "WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger from", "workflows runs. Because when an entity is added using the", "for k, v in kwargs.items(): if not isinstance(v, Promise): t", "input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs =", "That is, workflows should not call non-Flyte entities since they", "isinstance(results, VoidPromise) or results is None: continue # pragma: no", "Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more usage examples. :param _workflow_function:", "transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import", "ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers import logger", "f\"Binding data Promises have to be of the NodeOutput type", "using the add_entity function, all inputs to that entity should've", "t1() # In the former case we get the task's", "necessary to create an SdkWorkflow, except for the missing project", "if ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix,", "which are specified using the bindings list, and a map", "\" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} &&", "looks like the above but now we're doing it for", "raise FlyteValueException(results, f\"{results} received but should've been VoidPromise or None.\")", "done to support the invariant that Workflow local executions always", "1: return bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This", "specified using the bindings list, and a map of nodes", "be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn))", "information. \"\"\" def __init__( self, workflow_function: Callable, metadata: Optional[WorkflowMetadata], default_metadata:", "For PythonFunctionWorkflows, the Python function is run, for the ImperativeWorkflow,", "a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]:", "nodes in order. for node in self.compilation_state.nodes: if node not", "looking at the function's signature, workflows need to run through", "lengths {results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] =", "failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): metadata", "f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \"", "Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs) # First", "CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import (", "if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name:", "Type, Union from flytekit.common import constants as _common_constants from flytekit.common.exceptions.user", "just here to help workflow authors detect issues a bit", "Workflows is close to, but not exactly, the call pattern", "v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through", "but elegant handling of them is not a high priority", "checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False if len(self._unbound_inputs)", "For local execution, it goes __call__ -> _local_execute -> execute", "_interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return self._output_bindings", "the workflow runs on Flyte. That is, workflows should not", "at least one node * All workflow inputs are bound", "because we don't prevent users from specifying inputs # as", "outputs, we create a map to start things off, filled", "DAG of tasks using the data flow between tasks. Unlike", "Promise-generating loop inside _local_execute too for k, v in input_kwargs.items():", "kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first", "and a map of nodes to its outputs. Basically this", "for naming outputs - and single-length-NamedTuples are # particularly troublesome", "import interface as _interface_models from flytekit.models import literals as _literal_models", "does store state. This loop adds Tasks that are defined", "output {output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx", "task resolver interface itself is # more or less stateless", "val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals = {}", "workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std( ctx, output_names[0], self.interface.outputs[output_names[0]].type,", "the one output might be a list. We don't want", "import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from", "that will turn a binding into a Promise object, using", "# Move along, nothing to assign # Because we should've", "workflow structure. It's also important to note that, local execution", "the NodeOutput type {type(binding_data.promise)} found\" ) # b.var is the", "That convention is used for naming outputs - and single-length-NamedTuples", "Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def", "All workflow inputs are bound These conditions assume that all", "super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) ->", "tuple, # if it's a single element then we return", "in resolving bindings, pulling in outputs from previously completed nodes", "already exists on your Flyte installation. This object will not", "self._local_execute(child_ctx, **input_kwargs) expected_outputs = len(self.python_interface.outputs) if expected_outputs == 0: if", "Node: return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) ->", "nothing to assign # Because we should've already returned in", "# def wf(): # t1() # In the former case", "_local_execute should've already ensured that all the values in kwargs", "and 2) what a user would return in mock function.", "interface provided causes an issue with compilation, an error will", "type(p) == dict: raise FlyteValidationException( f\"If specifying a list or", "= [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def", "self._output_bindings @property def nodes(self) -> List[Node]: return self._nodes def __repr__(self):", "return [input_value] # Every time an entity is added, mark", "returned in the above check, we just raise an error", "only one output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and", "f\"{results} received but should've been VoidPromise or None.\") # if", "is because we don't prevent users from specifying inputs #", "This Python object represents a workflow defined by a function", "name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState:", "__init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool]", "node's bindings require, # and then fill them in using", "workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[],", "!= WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy {self.on_failure} not acceptable\") def", "True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be", "isinstance(v, Promise): raise ValueError(f\"Received a promise for a workflow call,", "defined workflows is done node by node. This function will", "fill them in using the node output tracker map we", "names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for var in expected_output_names] return", "name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface", "@property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self):", "node by node. This function will fill in the node's", "is implicitly passed and represents the decorated function. :param failure_policy:", "WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} # This unbound", "object for additional information. \"\"\" def __init__( self, workflow_function: Callable,", "more or less stateless (the future-proofing get_all_tasks function notwithstanding). However", "invariant that Workflow local executions always work with Promise objects", "bindings list, and a map of nodes to its outputs.", "== ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and", "&& \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs}", "high-level understanding of what workflows are in Flyte. This Python", "and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes", "= p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name} from", "\"\"\" def wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project,", "import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals,", "more usage examples. :param _workflow_function: This argument is implicitly passed", "ctx: n = create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list):", "in a wf, a user can call a sub-workflow with", "with compilation, an error will be returned. \"\"\" def wrapper(fn)", "the list here, instead we should let the binding creation", "with an `else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std(", "in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else)", "import constants as _common_constants from flytekit.common.exceptions.user import FlyteValidationException, FlyteValueException from", "output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type})", "self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def", "add an entity, all the inputs to the entity must", "workflow class inherits from (ClassStorageTaskResolver) # does store state. This", "and single-length-NamedTuples are # particularly troublesome but elegant handling of", "named tuple, then we do a one-element non-named tuple, #", "AssertionError(\"Only Keyword Arguments are supported for Workflow executions\") ctx =", "key off of the name instead of value? all_input_values =", "str, name: str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]:", "that you've declared with add_workflow_input but haven't yet consumed. This", "__repr__(self): return ( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}):", "used in the compilation. This mimics a 'closure' in the", "in enumerate(function_outputs)} # Basically we need to repackage the promises", ") as comp_ctx: # Construct the default input promise bindings,", "outputs the same way as any other previous node. \"\"\"", "This decorator declares a function to be a Flyte workflow.", "not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {} # Retrieve the entity", "# TODO do we need this - can this not", "workflow execution has already been set. elif ( ctx.execution_state is", "else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i, _ in enumerate(function_outputs)}", "on that object for additional information. \"\"\" def __init__( self,", "not return at all # def wf(): # t1() #", "at a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name) #", "1: # Here we have to handle the fact that", "in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] = {}", "structure of a task by looking at the function's signature,", "keep track of its own compilation state. \"\"\" return self._compilation_state", "lookup map. Please see get_promise_map for the rest of the", "filter for those. # There's probably a way to clean", "from flytekit.models import literals as _literal_models from flytekit.models.core import workflow", "raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") # Create", "\"\"\" This decorator declares a function to be a Flyte", "workflow outputs bindings = [] output_names = list(self.interface.outputs.keys()) # The", "then it # should be a tuple here, if it's", "VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import", "two Workflow styles. For PythonFunctionWorkflows, the Python function is run,", "single-length-NamedTuples are # particularly troublesome but elegant handling of them", "the options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks", "output_tuple(*nones) else: return None # We are already in a", "when an entity is added using the add_entity function, all", "function itself because the body of the function is what", "len(self.python_interface.outputs) == 0: return VoidPromise(self.name) # The values that we", "[] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return self._name", "rest of the details. \"\"\" if binding_data.promise is not None:", "sub-workflow with a Python native value. for k, v in", "_workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure:", "to the workflow # object itself. for n in comp_ctx.compilation_state.nodes:", "= r # The rest of this function looks like", "handle the fact that the wf could've been declared with", "we can just iterate through the nodes in order and", "-> Promise: \"\"\" This is a helper function that will", "execution, just continue the execution context return self._local_execute(ctx, **input_kwargs) #", "of them is not a high priority # Again, we're", "from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context()", "= {} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache)", "translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises", "Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults", "ValueError(\"expected outputs and actual outputs do not match\") def execute(self,", "VoidPromise(self.name) # Because we should've already returned in the above", "-> _interface_models.TypedInterface: return self._interface @property def output_bindings(self) -> List[_literal_models.Binding]: return", "workflow. Workflows are declarative entities that construct a DAG of", "with add_workflow_input but haven't yet consumed. This # is an", "Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): metadata =", "<flytekit.workflow>` decorator. Please see notes on that object for additional", "least one node * All workflow inputs are bound These", "get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if", "**kwargs): \"\"\" This function is here only to try to", "just raise an Exception here. if len(entity.python_interface.outputs) == 0: raise", "of the input to the task # binding_data.promise.var is the", "from flytekit.core.promise import ( NodeOutput, Promise, VoidPromise, binding_from_python_std, create_and_link_node, create_native_named_tuple,", "\"\"\" This class is similarly named to the one above.", "self._inputs = {} self._unbound_inputs = set() self._nodes = [] self._output_bindings:", "through the nodes in order. for node in self.compilation_state.nodes: if", "= None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def", "compile(self, **kwargs): \"\"\" Supply static Python native values in the", "= set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self)", "interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs, interface.outputs)", "inherits from (ClassStorageTaskResolver) # does store state. This loop adds", "one node * All workflow inputs are bound These conditions", "nodes(self) -> List[Node]: return self._nodes def __repr__(self): return ( f\"WorkflowBase", "b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class", "signature, workflows need to run through the function itself because", "tuple, then it # should be a tuple here, if", "essentially, this WorkflowMetadataDefaults class represents the defaults that are handed", "def wf(): # t1() # In the former case we", "None if len(output_names) == 1: return bindings[0] return tuple(bindings) def", "{len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError( \"Outputs specification", "for more usage examples. :param _workflow_function: This argument is implicitly", "only run once (again, this is with respect to the", ":param _workflow_function: This argument is implicitly passed and represents the", "not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx,", "it's a one element named tuple, then we do a", "is why the user is asked to provide the expected", "if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding data Promises have", "is used for naming outputs - and single-length-NamedTuples are #", "bindings, but then override with the provided inputs, if any", "def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self,", "return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly", "a combination of Python native values and Promises containing Flyte", "just # keeps track of workflow inputs that you've declared", "output_names[0], self.interface.outputs[output_names[0]].type, workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1:", ") bindings.append(b) # Save all the things necessary to create", "call a sub-workflow with a Python native value. for k,", "we return a single element if len(self.output_bindings) == 1: #", "list. We don't want to # iterate through the list", "flytekit.core.base_task import PythonTask from flytekit.core.class_based_resolver import ClassStorageTaskResolver from flytekit.core.condition import", "# There's probably a way to clean this up, maybe", "all nodes and workflow i/o changes were done with the", "self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) # This little loop", "for the missing project and domain self._nodes = all_nodes self._output_bindings", "any dependency issues. That is, we force the user to", "Dict[Node, Dict[str, Promise]] # Start things off with the outputs", "compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b = binding_from_python_std( ctx, output_name,", "function notwithstanding). However the # implementation of the TaskResolverMixin that", "prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\"", "# b.var is the name of the input to the", "we should let the binding creation unwrap it and make", "tuple([get_promise(b.binding, intermediate_node_outputs) for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask,", "reason the length 1 case is separate is because the", "node at a time. if len(self.python_interface.outputs) == 0: return VoidPromise(self.name)", "-> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static", "local execution, it goes __call__ -> _local_execute -> execute From", "r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of", "here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results} received but", "provided causes an issue with compilation, an error will be", "out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all the", "{self._python_interface.outputs} && \" f\"Output bindings: {self._output_bindings} && \" ) def", "called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]:", ":param interruptible: Whether or not tasks launched from this workflow", "add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def", "expected 0 outputs but something received {result}\") if (1 <", "then fill them in using the node output tracker map", "launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self,", "Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow(", "1 case is separate is because the one output might", "= python_interface self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs =", "using a lookup map. Please see get_promise_map for the rest", "else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow", "In the former case we get the task's VoidPromise, in", "and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity)", "except for the missing project and domain self._nodes = all_nodes", "inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name,", "id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY =", "of imperatively defined workflows is done node by node. This", "to a workflow's tasks, whereas WorkflowMetadata represents metadata about the", "BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables = [k for k", "but return value is a tuple\" ) workflow_outputs = workflow_outputs[0]", "Enum from typing import Any, Callable, Dict, List, Optional, Tuple,", "this loop. The reason is because we don't prevent users", "just one node at a time. if len(self.python_interface.outputs) == 0:", "object will not initiate a network call to Admin, which", "else: return [input_value] # Every time an entity is added,", "n def add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\"", "Adds an input to the workflow. \"\"\" if input_name in", "in this map. After all nodes are run, we fill", "This function is how local execution for imperative workflows runs.", "holds the outputs of each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}}", "task, the function body of a workflow is evaluated at", "= list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we have", "return None if len(output_names) == 1: return bindings[0] return tuple(bindings)", "list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we have to", "for k in self.interface.inputs.keys()]) input_kwargs.update(kwargs) workflow_outputs = self._workflow_function(**input_kwargs) all_nodes.extend(comp_ctx.compilation_state.nodes) #", "def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\"", "Tasks that are defined within the body of the workflow", "not tasks launched from this workflow are by default interruptible", "do additional checking. \"\"\" if len(self.compilation_state.nodes) == 0: return False", "this workflow class inherits from (ClassStorageTaskResolver) # does store state.", "are run, we fill in workflow level outputs the same", "super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called", "def wf(): # return t1() # or it may not", "is not None and expected_outputs == 1): return create_native_named_tuple(ctx, result,", "have to handle the fact that the wf could've been", "-> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs)", "k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None", "{} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return", "self._compilation_state.nodes @property def inputs(self) -> Dict[str, Promise]: \"\"\" This holds", "return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read", "call an execute inside _local_execute. This makes mocking cleaner. \"\"\"", "do we need this - can this not be in", "class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE )", "FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy", "var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str, p:", "in the above check, we just raise an error here.", "VoidPromise): return None else: raise Exception(f\"Workflow local execution expected 0", "along, nothing to assign # Because we should've already returned", "time the interface provided causes an issue with compilation, an", "flytekit.models import interface as _interface_models from flytekit.models import literals as", "(aka compile-time). This is because while we can determine the", "node. \"\"\" return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes", "only one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)}", "Here we have to handle the fact that the wf", "the calling and outputs of each node's entity results =", "[] output_names = list(self.interface.outputs.keys()) # The reason the length 1", "to be of the NodeOutput type {type(binding_data.promise)} found\" ) #", "# Start things off with the outputs of the global", "{}} # type: Dict[Node, Dict[str, Promise]] # Start things off", "{n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs bindings =", "from the output have to be pulled by fulfilling all", "return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first", "is not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state))", "launch plan only, but is here only so that we", "list, and a map of nodes to its outputs. Basically", "but we're only interested in the ones that are Promises", "at a time. \"\"\" if len(args) > 0: raise AssertionError(\"Only", "the # workflow's output bindings. # The return style here", "support the invariant that Workflow local executions always work with", "output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already", "Any]], ReferenceWorkflow]: \"\"\" A reference workflow is a pointer to", "super().__init__(**kwargs) @property def name(self) -> str: return self._name @property def", "-> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property", "task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def add_launch_plan(self,", "are bound These conditions assume that all nodes and workflow", "\"\"\" This function returns whether or not the workflow is", "starting with the container type (e.g. List[int]\" ) python_type =", "# holding Flyte literal values. Even in a wf, a", "done a bit at a time, one task or other", "if len(self._unbound_inputs) > 0: return False return True class PythonFunctionWorkflow(WorkflowBase,", "the nodes in order. for node in self.compilation_state.nodes: if node", "self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node:", "block (if-else) should always end with an `else_()` clause\") t", "return VoidPromise(self.name) # Because we should've already returned in the", "are declarative entities that construct a DAG of tasks using", "Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface", "in workflow level outputs the same way as any other", "output have to be pulled by fulfilling all of the", "type(p) == list or type(p) == dict: raise FlyteValidationException( f\"If", "a Flyte workflow. Workflows are declarative entities that construct a", "def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible:", "def __call__(self, *args, **kwargs): \"\"\" The call pattern for Workflows", "is not None: if not isinstance(binding_data.promise, NodeOutput): raise FlyteValidationException( f\"Binding", "{k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result", "entity from the node, and call it by looking up", "then we do a one-element non-named tuple, # if it's", "return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper class", "the expected interface. If at registration time the interface provided", "-> _local_execute -> execute From execute, different things happen for", "outputs) def reference_workflow( project: str, domain: str, name: str, version:", "self.interface.inputs[k].type)) # The output of this will always be a", "ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode,", "@property def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface:", "[] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if isinstance(input_value,", "return self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node:", "= {expected_output_names[0]: function_outputs} else: wf_outputs_as_map = {expected_output_names[i]: function_outputs[i] for i,", "a high-level understanding of what workflows are in Flyte. This", "in kwargs are Promise objects for k, v in kwargs.items():", "if isinstance(workflow_outputs[i], ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always", "compilation, an error will be returned. \"\"\" def wrapper(fn) ->", "{output_name} already exists in workflow {self.name}\") if python_type is None:", "input_kwargs.items(): if k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword", "= entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results", "outputs. Basically this takes the place of propeller in resolving", "# does store state. This loop adds Tasks that are", "nodes to its outputs. Basically this takes the place of", "__call__(self, *args, **kwargs): \"\"\" The call pattern for Workflows is", "Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version),", "is added using the add_entity function, all inputs to that", "metadata: Optional[WorkflowMetadata], default_metadata: Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function =", "None: continue # pragma: no cover # Move along, nothing", "add_entity function, all inputs to that entity should've been already", "not ready, wf is currently {self}\") # Create a map", "from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if ctx.compilation_state is", "Supply static Python native values in the kwargs if you", "This is because while we can determine the entire structure", "kwargs.items(): if not isinstance(v, Promise): t = self.python_interface.inputs[k] kwargs[k] =", "been set. elif ( ctx.execution_state is not None and ctx.execution_state.mode", ") workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return", "passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition", "specifying inputs # as direct scalars, which means there's another", "outputs.\", ) return VoidPromise(self.name) # Because we should've already returned", "Promise: \"\"\" This is a helper function that will turn", "# workflow's output bindings. # The return style here has", "to the workflow. The nodes in these Promise objects should", "wrapper(fn) -> ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name,", "entities already in a topological sort. To keep track of", "len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification indicates only", "intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str, Promise]] #", "and isinstance(function_outputs, tuple): wf_outputs_as_map = {expected_output_names[0]: function_outputs[0]} else: wf_outputs_as_map =", "of outputs, we create a map to start things off,", "name instead of value? all_input_values = get_input_values(kwargs) for input_value in", "): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults", "to that entity should've been already declared, we can just", "an error that Admin would return at compile time anyways,", "or other entity call at a time. This is why", "create a map to start things off, filled in only", "(if any). As things are run, their outputs are stored", "for those. # There's probably a way to clean this", "- can this not be in launchplan only? # This", "the platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for", "as part of the task resolver change. The task resolver", "the inputs to the entity must be bound. \"\"\" #", "outputs but something received {result}\") if (1 < expected_outputs ==", "calling and outputs of each node's entity results = entity(**entity_kwargs)", "body of the function is what expresses the workflow structure.", "been already declared, we can just iterate through the nodes", "use the workflow's output names. new_promises = [Promise(var, wf_outputs_as_literal_dict[var]) for", "not True and self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must", "Interface, **kwargs, ): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults", "literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not", "if ctx.compilation_state is not None: raise Exception(\"Can't already be compiling\")", "\"\"\" Supply static Python native values in the kwargs if", "an Exception here. if len(entity.python_interface.outputs) == 0: raise FlyteValueException(results, f\"{results}", "the name of the upstream node's output we want return", "= [] for x in input_value: input_promises.extend(get_input_values(x)) return input_promises if", "= WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\")", "conditions assume that all nodes and workflow i/o changes were", "import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import", "wf, a user can call a sub-workflow with a Python", "platform, local runs notwithstanding). Please see the :std:doc:`cookbook:sphx_glr_auto_core_flyte_basics_basic_workflow.py` for more", "**kwargs) -> Node: return self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase,", "by default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or", "to note that, local execution notwithstanding, it is not evaluated", "outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs)", "as part of a parent's workflow local run. # The", "result is None or isinstance(result, VoidPromise): return None else: raise", "will gather all the input # values but we're only", "if len(results) != len(expected_output_names): raise FlyteValueException(results, f\"Different lengths {results} {expected_output_names}\")", "result, self.python_interface) raise ValueError(\"expected outputs and actual outputs do not", "tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b =", "# collection/map out of it. if len(output_names) == 1: if", "is added, mark it as used. The above function though", "element named tuple, then we do a one-element non-named tuple,", "specification indicates multiple return values, received only one\") if len(output_names)", "def __init__( self, name: str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface:", "already returned in the above check, we just raise an", "# object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask)", "they are only run once (again, this is with respect", "bindings: entity_kwargs[b.var] = get_promise(b.binding, outputs_cache) return entity_kwargs class WorkflowBase(object): def", "Dict[str, Promise]: \"\"\" Local execution of imperatively defined workflows is", "# Run some sanity checks # Even though the _local_execute", "flytekit to raise # the error earlier. self._unbound_inputs = set()", "an error will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow:", "return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element return", "already in a topological sort. To keep track of outputs,", "when this workflow (self) is being called as part of", "a 'closure' in the traditional sense of the word. \"\"\"", "whether or not the workflow is in a ready state,", "output_tuple_name as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map", "is what expresses the workflow structure. It's also important to", "FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters,", "# if there's only one output, if len(expected_output_names) == 1:", "one. That convention is used for naming outputs - and", "them to be used in the compilation. This mimics a", "len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow", "outputs and actual outputs do not match\") def execute(self, **kwargs):", "interface itself is # more or less stateless (the future-proofing", "case is separate is because the one output might be", "is asked to provide the expected interface. If at registration", "if binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput): raise", "binding_from_python_std, create_and_link_node, create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask", "return None # We are already in a local execution,", "local executions always work with Promise objects # holding Flyte", "for var in expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def", "raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in", "- and single-length-NamedTuples are # particularly troublesome but elegant handling", "of this function looks like the above but now we're", "resolver interface itself is # more or less stateless (the", "to match what 1) what the workflow would've returned had", "information but essentially, this WorkflowMetadataDefaults class represents the defaults that", "var=\"placeholder\", val=_literal_models.Literal(map=_literal_models.LiteralMap(literals=literals)) ) raise FlyteValidationException(\"Binding type unrecognized.\") def get_promise_map( bindings:", "a local workflow execution else: # Run some sanity checks", "create_node(entity=entity, **kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises = []", "inputs, outputs) def reference_workflow( project: str, domain: str, name: str,", "flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched from this", "construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name", "start things off, filled in only with the workflow inputs", "return ( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs}", "has already been specified for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name:", "workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\"", "`else_()` clause\") t = self.python_interface.outputs[out] b = binding_from_python_std( ctx, out,", "self.add_entity(launch_plan, **kwargs) def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return", "flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = (", "ReferenceWorkflow]: \"\"\" A reference workflow is a pointer to a", "length 1 case is separate is because the one output", "literal values. Even in a wf, a user can call", "bit at a time, one task or other entity call", "= len(self.python_interface.outputs) if expected_outputs == 0: if result is None", "a ready state, which means * Has at least one", "Workflow local executions always work with Promise objects # holding", ") from flytekit.core.launch_plan import LaunchPlan from flytekit.core.node import Node from", "__post_init__(self): if self.interruptible is not True and self.interruptible is not", "in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value] # Every", "is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This", "FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible)", "def workflow_metadata(self) -> Optional[WorkflowMetadata]: return self._workflow_metadata @property def workflow_metadata_defaults(self): return", "len(self._unbound_inputs) > 0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver):", "entity should've been already declared, we can just iterate through", "def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self,", "function_outputs, f\"{function_outputs} received but should've been VoidPromise or None.\" )", "None if isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs)", "self._interface = transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes", "To keep track of outputs, we create a map to", "that this workflow class inherits from (ClassStorageTaskResolver) # does store", "== 1: # Here we have to handle the fact", "add_workflow_input(self, input_name: str, python_type: Type) -> Interface: \"\"\" Adds an", "workflows is done node by node. This function will fill", "bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise", "Tuple, Type, Union from flytekit.common import constants as _common_constants from", "ctx.execution_state is not None and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if", "workflow authors detect issues a bit earlier. It just #", "class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to the", "The above function though will gather all the input #", "t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\"", "the entity must be bound. \"\"\" # circular import from", "the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that object", "__init__( self, project: str, domain: str, name: str, version: str,", "is done a bit at a time, one task or", "if isinstance(input_value, dict): input_promises = [] for _, v in", "return self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\"", "have to be of the NodeOutput type {type(binding_data.promise)} found\" )", "execute(self, **kwargs): \"\"\" Called by _local_execute. This function is how", "intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this function looks", "outputs are stored in this map. After all nodes are", ") class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY = _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE", "declarative entities that construct a DAG of tasks using the", "Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) ->", "above but now we're doing it for the workflow as", "k not in self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\")", "return entity_kwargs class WorkflowBase(object): def __init__( self, name: str, workflow_metadata:", "previously completed nodes and filling in the necessary inputs. \"\"\"", "Because when an entity is added using the add_entity function,", "as a whole rather # than just one node at", "elegant handling of them is not a high priority #", "them is not a high priority # Again, we're using", "other previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not", "Optional, Tuple, Type, Union from flytekit.common import constants as _common_constants", "**kwargs, ): self._name = name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults =", "we shouldn't run into any dependency issues. That is, we", "local execution for imperative workflows runs. Because when an entity", "want to # iterate through the list here, instead we", "self._nodes = all_nodes self._output_bindings = bindings if not output_names: return", "interruptible: Optional[bool] = False, ): \"\"\" This decorator declares a", "# Basically we need to repackage the promises coming from", "comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name}", "given node output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output", "a Python native value. for k, v in kwargs.items(): if", "list(self.interface.outputs.keys()) # The reason the length 1 case is separate", "-> Interface: \"\"\" Adds an input to the workflow. \"\"\"", "node output. \"\"\" if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name}", "str, name: str, version: str, inputs: Dict[str, Type], outputs: Dict[str,", "is None: raise AssertionError( \"Outputs specification for Workflow does not", "should've been VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if", "entity is added using the add_entity function, all inputs to", "native value. for k, v in kwargs.items(): if not isinstance(v,", "non-Flyte entities since they are only run once (again, this", "python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\" Compilation is", "!= len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i,", "node.flyte_entity entity_kwargs = get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and", "BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import", "adds Tasks that are defined within the body of the", "an SdkWorkflow, except for the missing project and domain self._nodes", "{} for k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache)", "= self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) #", "\"\"\" This is a helper function that will turn a", "collections.namedtuple(self.python_interface.output_tuple_name, variables) nones = [None for _ in self.python_interface.outputs.keys()] return", "one\") if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs", "a task that doesn't return anything # def wf(): #", "handed down to a workflow's tasks, whereas WorkflowMetadata represents metadata", "saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs", "import ClassStorageTaskResolver from flytekit.core.condition import ConditionalSection from flytekit.core.context_manager import (", "function returns whether or not the workflow is in a", "enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this function", "place of propeller in resolving bindings, pulling in outputs from", "and ctx.execution_state.mode == ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION ): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if", "idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest", "set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self)", "compilation state. \"\"\" return self._compilation_state @property def nodes(self) -> List[Node]:", "user can call a sub-workflow with a Python native value.", "p: Union[Promise, List[Promise], Dict[str, Promise]], python_type: Optional[Type] = None ):", "or type(p) == dict: raise FlyteValidationException( f\"If specifying a list", "only? # This can be in launch plan only, but", "compile time anyways, but this allows flytekit to raise #", "instead we should let the binding creation unwrap it and", "exactly, the call pattern for Tasks. For local execution, it", "here only to try to streamline the pattern between workflows", "entity_kwargs = {} for b in bindings: entity_kwargs[b.var] = get_promise(b.binding,", "_literal_models from flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node(", "Workflow executions\") ctx = FlyteContextManager.current_context() # Get default agruements and", "self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface @property def", "{results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r", "def add_subwf(self, sub_wf: WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs)", "a tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b", ") workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]] b = binding_from_python_std(", "for k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k]", "@property def function(self): return self._workflow_function def task_name(self, t: PythonAutoContainerTask) ->", "Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of this", "we just raise an error here. if len(self.python_interface.outputs) == 0:", "name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function", "ctx.compilation_state is not None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) #", "workflow as a whole rather # than just one node", "1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates", "has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) # Because we should've", "received but should've been VoidPromise or None.\" ) expected_output_names =", "circular import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context() if", "or function_outputs is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException(", "ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = []", "This object will not initiate a network call to Admin,", "be called\") def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise,", "because the one output might be a list. We don't", "if not output_names: return None if len(output_names) == 1: return", "# This little loop was added as part of the", "= transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs, interface.outputs) return", "Retrieve the entity from the node, and call it by", "off of the name instead of value? all_input_values = get_input_values(kwargs)", "evaluated at serialization-time (aka compile-time). This is because while we", "need to run through the function itself because the body", "\"\"\" Anytime you add an entity, all the inputs to", "\" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} &&", "def workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return", "can call a sub-workflow with a Python native value. for", "literals, and creating new Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map,", "= name self._workflow_metadata = workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface =", "but is here only so that we don't have to", "not None: raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as", "but then override with the provided inputs, if any input_kwargs", "a whole rather # than just one node at a", "\"\"\" return self._inputs def __repr__(self): return super().__repr__() + f\"Nodes ({len(self.compilation_state.nodes)}):", "Python function is run, for the ImperativeWorkflow, each node is", "ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a pointer to", "outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is a", "separate is because the one output might be a list.", "styles. For PythonFunctionWorkflows, the Python function is run, for the", "all_nodes self._output_bindings = bindings if not output_names: return None if", "outputs of each node's entity results = entity(**entity_kwargs) expected_output_names =", "it for the workflow as a whole rather # than", "bool: \"\"\" This function returns whether or not the workflow", "**kwargs): raise Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext,", "is how local execution for imperative workflows runs. Because when", "of tasks using the data flow between tasks. Unlike a", "add_task(self, task: PythonTask, **kwargs) -> Node: return self.add_entity(task, **kwargs) def", "Promise object, using a lookup map. Please see get_promise_map for", "def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name:", "workflow_instance.compile() return workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper", "flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is not", "all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not", "and tasks. Since tasks call execute from dispatch_execute which is", "kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the nodes", "# Because we should've already returned in the above check,", "WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name = name", "another Promise-generating loop inside _local_execute too for k, v in", "Promises wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) #", "FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) -> str: return self._name @property", "output_names: return None if len(output_names) == 1: return bindings[0] return", "return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit", "None.\") # if there's only one output, if len(expected_output_names) ==", "raise AssertionError(\"The Workflow specification indicates multiple return values, received only", "one node at a time. if len(self.python_interface.outputs) == 0: return", "**kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool:", "f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python native values", "ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the default input", "iterate through the nodes in order. for node in self.compilation_state.nodes:", "outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is", "bindings[0] return tuple(bindings) def execute(self, **kwargs): \"\"\" This function is", "Last is starting a local workflow execution else: # Run", "a network call to Admin, which is why the user", "if result is None or isinstance(result, VoidPromise): return None else:", "\"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is", "WorkflowBase, **kwargs) -> Node: return self.add_entity(sub_wf, **kwargs) def ready(self) ->", "whole rather # than just one node at a time.", "if it's a one element named tuple, then we do", "return self._compilation_state @property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property", "wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance", "is here only to try to streamline the pattern between", "because while we can determine the entire structure of a", "function is here only to try to streamline the pattern", "ReferenceWorkflow: interface = transform_signature_to_interface(inspect.signature(fn)) return ReferenceWorkflow(project, domain, name, version, interface.inputs,", "f\"{ctx.compilation_state.prefix}-{self.short_name}-\" if ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context(", "each node's entity results = entity(**entity_kwargs) expected_output_names = list(entity.python_interface.outputs.keys()) if", "input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str,", "which is why the user is asked to provide the", "be in launchplan only? # This can be in launch", "# Save all the things necessary to create an SdkWorkflow,", "a pointer to a workflow that already exists on your", "f\"If specifying a list or dict of Promises, you must", "class has to keep track of its own compilation state.", "expected_output_names = list(entity.python_interface.outputs.keys()) if isinstance(results, VoidPromise) or results is None:", "have to do the # conversion here in this loop.", "into Promises that match the workflow's # interface. We do", "in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val return", "to be used in the compilation. This mimics a 'closure'", "ValueError(f\"Received a promise for a workflow call, when expecting a", "a user can call a sub-workflow with a Python native", "WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add an entity,", "in the latter we get None if isinstance(function_outputs, VoidPromise) or", "self.execute(**kwargs) # First handle the empty return case. # A", "in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs:", "a helper function that will turn a binding into a", "return a task that doesn't return anything # def wf():", "values and Promises containing Flyte # Literals. function_outputs = self.execute(**kwargs)", "\"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] = None,", "str, inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project, domain,", "its own compilation state. \"\"\" return self._compilation_state @property def nodes(self)", "an entity, all the inputs to the entity must be", "by _local_execute. This function is how local execution for imperative", "ctx.compilation_state is not None: raise Exception(\"Can't already be compiling\") with", "necessary inputs. \"\"\" entity_kwargs = {} for b in bindings:", "({len(self.compilation_state.nodes)}): {self.compilation_state.nodes}\" def execute(self, **kwargs): \"\"\" Called by _local_execute. This", "conversion here in this loop. The reason is because we", "def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\"", "str, workflow_metadata: WorkflowMetadata, workflow_metadata_defaults: WorkflowMetadataDefaults, python_interface: Interface, **kwargs, ): self._name", "means * Has at least one node * All workflow", "0: return False return True class PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please", "from this workflow are by default interruptible \"\"\" def wrapper(fn):", "input to the workflow. \"\"\" if input_name in self._inputs: raise", "n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\") self.add(n.flyte_entity) #", "and call it by looking up the promises the node's", "(e.g. List[int]\" ) python_type = p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for", "f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do", "= transform_interface_to_typed_interface(self._python_interface) self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name]", "as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None,", "in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The rest of this", "to understand that we're dealing with a one-element # named", "Workflow styles. For PythonFunctionWorkflows, the Python function is run, for", "execution, it goes __call__ -> _local_execute -> execute From execute,", "are supported for Workflow executions\") ctx = FlyteContextManager.current_context() # Get", "= None, interruptible: Optional[bool] = False, ): metadata = WorkflowMetadata(on_failure=failure_policy", "but this allows flytekit to raise # the error earlier.", "the promises the node's bindings require, # and then fill", "The values that we return below from the output have", "import ConditionalSection from flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext,", "if isinstance(function_outputs, VoidPromise) or function_outputs is None: if len(self.python_interface.outputs) !=", "Add an output with the given name from the given", "= WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile()", "( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise", "= binding_from_python_std( ctx, output_name, expected_literal_type=flyte_type, t_value=p, t_value_type=python_type ) self._output_bindings.append(b) self._python_interface", "Even in a wf, a user can call a sub-workflow", "p.ref.node.flyte_entity.python_interface.outputs[p.var] logger.debug(f\"Inferring python type for wf output {output_name} from Promise", "self.interruptible is not False: raise FlyteValidationException(f\"Interruptible must be boolean, {self.interruptible}", "self._unbound_inputs = set() self._nodes = [] self._output_bindings: Optional[List[_literal_models.Binding]] = []", "if self.interruptible is not True and self.interruptible is not False:", "get_promise(bd, outputs_cache) literals.append(p.val) return Promise( var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map", "this workflow are by default interruptible \"\"\" def wrapper(fn): workflow_metadata", "entity call at a time. This is why this workflow", "interested in the ones that are Promises so let's filter", "an issue with compilation, an error will be returned. \"\"\"", "all # def wf(): # t1() # In the former", "self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1] @property def", "This argument is implicitly passed and represents the decorated function.", "raise Exception(\"Should not be called\") def _local_execute(self, ctx: FlyteContext, **kwargs)", "default agruements and override with kwargs passed in input_kwargs =", "value, received {len(workflow_outputs)}\" ) if self.python_interface.output_tuple_name is None: raise AssertionError(", "parent's workflow local run. # The context specifying the local", "static Python native values in the kwargs if you want", "done node by node. This function will fill in the", "we can re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata,", "flytekit.core.reference_entity import ReferenceEntity, WorkflowReference from flytekit.core.type_engine import TypeEngine from flytekit.loggers", "at a time, one task or other entity call at", "to be pulled by fulfilling all of the # workflow's", "consumed. This # is an error that Admin would return", "# Last is starting a local workflow execution else: #", "a bit earlier. It just # keeps track of workflow", "# should be a tuple here, if it's a one", "the output have to be pulled by fulfilling all of", "to try to streamline the pattern between workflows and tasks.", "to raise # the error earlier. self._unbound_inputs = set() super().__init__(", "enum import Enum from typing import Any, Callable, Dict, List,", "should've already ensured that all the values in kwargs are", "invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return {", "workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), ) @property def compilation_state(self) -> CompilationState: \"\"\" Compilation", "_local_execute, workflows should also call an execute inside _local_execute. This", "**kwargs) def get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for", "_workflow_function: This argument is implicitly passed and represents the decorated", "_ in enumerate(function_outputs)} # Basically we need to repackage the", "kwargs if you want them to be used in the", "version: str, inputs: Dict[str, Type], outputs: Dict[str, Type] ): super().__init__(WorkflowReference(project,", "raise FlyteValueException( function_outputs, f\"{function_outputs} received but interface has {len(self.python_interface.outputs)} outputs.\",", "{input_name} has already been specified for wf {self.name}.\") self._python_interface =", "transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this - can this", "the above check, we just raise an error here. if", "FlyteValidationException(f\"Workflow not ready, wf is currently {self}\") # Create a", "workflow call, when expecting a native value for {k}\") with", "always be a combination of Python native values and Promises", "self._output_bindings: Optional[List[_literal_models.Binding]] = [] FlyteEntities.entities.append(self) super().__init__(**kwargs) @property def name(self) ->", "holds the input promises to the workflow. The nodes in", "and outputs of each node's entity results = entity(**entity_kwargs) expected_output_names", "results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) != len(expected_output_names):", "is run, for the ImperativeWorkflow, each node is run one", "would return in mock function. That is, if it's a", "def _local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: #", "type {type(binding_data.promise)} found\" ) # b.var is the name of", "workflow inputs (if any). As things are run, their outputs", "we get None if isinstance(function_outputs, VoidPromise) or function_outputs is None:", "Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: b =", "with the provided inputs, if any input_kwargs = construct_input_promises([k for", "# Here we have to handle the fact that the", "in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\")", "for i, _ in enumerate(function_outputs)} # Basically we need to", "That is, if it's a tuple, then it # should", "provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state", "and then fill them in using the node output tracker", "imperatively defined workflows is done node by node. This function", "* Has at least one node * All workflow inputs", "with Promise objects # holding Flyte literal values. Even in", "(ClassStorageTaskResolver) # does store state. This loop adds Tasks that", "): if ctx.execution_state.branch_eval_mode == BranchEvalMode.BRANCH_SKIPPED: if self.python_interface and self.python_interface.output_tuple_name: variables", "earlier. It just # keeps track of workflow inputs that", "add_workflow_input but haven't yet consumed. This # is an error", "don't have to re-evaluate. Or # we can re-evaluate. self._input_parameters", "specifying the local workflow execution has already been set. elif", "input node, i.e. the inputs to the workflow. # _local_execute", "implicitly passed and represents the decorated function. :param failure_policy: Use", "state. \"\"\" return self._compilation_state @property def nodes(self) -> List[Node]: return", "workflow inputs are bound These conditions assume that all nodes", "in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) ->", "values in the kwargs if you want them to be", "a tuple here, if it's a one element named tuple,", "it and make a binding # collection/map out of it.", "literals = {} for k, bd in binding_data.map.bindings.items(): p =", "provide the expected interface. If at registration time the interface", "node in self.compilation_state.nodes: if node not in intermediate_node_outputs.keys(): intermediate_node_outputs[node] =", "not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification indicates multiple return", "flytekit.models.core import workflow as _workflow_model GLOBAL_START_NODE = Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None,", "need this - can this not be in launchplan only?", "# This can be in launch plan only, but is", "in order. for node in self.compilation_state.nodes: if node not in", "{self.name}\") if python_type is None: if type(p) == list or", "and actual outputs do not match\") def execute(self, **kwargs): raise", "is a helper function that will turn a binding into", "0: raise AssertionError(\"Only Keyword Arguments are supported for Workflow executions\")", "str, domain: str, name: str, version: str, inputs: Dict[str, Type],", "and override with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs)", "-> execute From execute, different things happen for the two", "import annotations import collections import inspect from dataclasses import dataclass", "flytekit.core.context_manager import ( BranchEvalMode, CompilationState, ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, )", "from __future__ import annotations import collections import inspect from dataclasses", "above. Please see the IDL for more information but essentially,", "the former case we get the task's VoidPromise, in the", "self.add_entity(task, **kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return", "return self._name @property def short_name(self) -> str: return self._name.split(\".\")[-1] @property", "isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task", "return a single element if len(self.output_bindings) == 1: # Again", "): super().__init__(WorkflowReference(project, domain, name, version), inputs, outputs) def reference_workflow( project:", "bindings: {self._output_bindings} && \" ) def __call__(self, *args, **kwargs): \"\"\"", "a one-element non-named tuple, # if it's a single element", "we can determine the entire structure of a task by", "FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix =", "len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] =", "inputs to the entity must be bound. \"\"\" # circular", "already ensured that all the values in kwargs are Promise", "local run. # The context specifying the local workflow execution", "received {result}\") if (1 < expected_outputs == len(result)) or (result", "will always be a combination of Python native values and", "try to streamline the pattern between workflows and tasks. Since", "raise an error here. if len(self.python_interface.outputs) == 0: raise FlyteValueException(", "will be returned. \"\"\" def wrapper(fn) -> ReferenceWorkflow: interface =", "keeps track of workflow inputs that you've declared with add_workflow_input", "to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else: on_failure", "Flyte literal values. Even in a wf, a user can", "workflow i/o changes were done with the functions above, which", "mismatch {len(output_names)} vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if", "Node( id=_common_constants.GLOBAL_INPUT_NODE_ID, metadata=None, bindings=[], upstream_nodes=[], flyte_entity=None, ) class WorkflowFailurePolicy(Enum): FAIL_IMMEDIATELY", "represents a workflow defined by a function and decorated with", "PythonAutoContainerTask) and n.flyte_entity.task_resolver == self: logger.debug(f\"WF {self.name} saving task {n.flyte_entity.name}\")", "return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return self._interface @property", "those. # There's probably a way to clean this up,", "# Next iterate through the nodes in order. for node", "up, maybe key off of the name instead of value?", "@dataclass class WorkflowMetadataDefaults(object): \"\"\" This class is similarly named to", "compilation, an error will be returned. \"\"\" def __init__( self,", "with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct the", "ctx = FlyteContextManager.current_context() # Get default agruements and override with", "shouldn't run into any dependency issues. That is, we force", "not exactly, the call pattern for Tasks. For local execution,", "a workflow defined by a function and decorated with the", "Construct the default input promise bindings, but then override with", "CompilationState: \"\"\" Compilation is done a bit at a time,", "str: return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python", "Recreate new promises that use the workflow's output names. new_promises", "them in using the node output tracker map we have.", "return False if len(self._unbound_inputs) > 0: return False return True", "str, version: str, inputs: Dict[str, Type], outputs: Dict[str, Type] ):", "output, if len(expected_output_names) == 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple):", "Flyte installation. This object will not initiate a network call", "issue with compilation, an error will be returned. \"\"\" def", "fulfilling all of the # workflow's output bindings. # The", "indicates multiple return values, received only one\") if len(output_names) !=", "runs. Because when an entity is added using the add_entity", "bit earlier. It just # keeps track of workflow inputs", "FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) ) ) as child_ctx: result = self._local_execute(child_ctx,", "are defined within the body of the workflow to the", "values in kwargs are Promise objects for k, v in", "on_failure = 0 else: on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass", "workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function def", "anything # def wf(): # return t1() # or it", "t, ) bindings.append(b) # Save all the things necessary to", "pulled by fulfilling all of the # workflow's output bindings.", "def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for", "Handle the calling and outputs of each node's entity results", "binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val return Promise(", "a Promise object, using a lookup map. Please see get_promise_map", "self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is compilation. if ctx.compilation_state", "nodes are run, we fill in workflow level outputs the", "one above. Please see the IDL for more information but", "Move along, nothing to assign # Because we should've already", "by looking at the function's signature, workflows need to run", "# circular import from flytekit.core.node_creation import create_node ctx = FlyteContext.current_context()", "Promise objects for k, v in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v", "= self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask,", "# The return style here has to match what 1)", "bindings if not output_names: return None if len(output_names) == 1:", "# binding_data.promise.var is the name of the upstream node's output", "False if len(self._unbound_inputs) > 0: return False return True class", "workflow_metadata_defaults(self): return self._workflow_metadata_defaults @property def python_interface(self) -> Interface: return self._python_interface", "tuple): if len(workflow_outputs) != 1: raise AssertionError( f\"The Workflow specification", "input promises to the workflow. The nodes in these Promise", "return value is a tuple\" ) workflow_outputs = workflow_outputs[0] t", "to # iterate through the list here, instead we should", "workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults ) workflow_instance.compile() return workflow_instance", "extracting out the literals, and creating new Promises wf_outputs_as_literal_dict =", "the compilation. This mimics a 'closure' in the traditional sense", "> 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The Workflow specification", "using the data flow between tasks. Unlike a task, the", "wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A reference workflow is a", "var=\"placeholder\", val=_literal_models.Literal(collection=_literal_models.LiteralCollection(literals=literals)), ) elif binding_data.map is not None: literals =", "= Promise(var=k, val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of", "elif len(output_names) > 1: if not isinstance(workflow_outputs, tuple): raise AssertionError(\"The", "1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else:", "CompilationState(prefix=\"\") self._inputs = {} # This unbound inputs construct is", "must be bound. \"\"\" # circular import from flytekit.core.node_creation import", "ExecutionState, FlyteContext, FlyteContextManager, FlyteEntities, ) from flytekit.core.interface import ( Interface,", "would return at compile time anyways, but this allows flytekit", "= transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes =", "from flytekit.loggers import logger from flytekit.models import interface as _interface_models", "boolean, {self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]):", "is a pointer to a workflow that already exists on", "we create a map to start things off, filled in", "== 1: if entity.python_interface.output_tuple_name and isinstance(results, tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0]", "which means * Has at least one node * All", "@property def inputs(self) -> Dict[str, Promise]: \"\"\" This holds the", "**kwargs) def add_launch_plan(self, launch_plan: LaunchPlan, **kwargs) -> Node: return self.add_entity(launch_plan,", "= FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix", "streamline the pattern between workflows and tasks. Since tasks call", "Dict[Node, Dict[str, Promise]]) -> Promise: \"\"\" This is a helper", "ctx = FlyteContext.current_context() if ctx.compilation_state is not None: raise Exception(\"Can't", "project and domain self._nodes = all_nodes self._output_bindings = bindings if", "python_interface: Interface, **kwargs, ): self._name = name self._workflow_metadata = workflow_metadata", "return style here has to match what 1) what the", "represents metadata about the workflow itself. \"\"\" interruptible: bool def", "of the workflow to the workflow # object itself. for", "the workflow is in a ready state, which means *", "if output_name in self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in", "len(self.python_interface.outputs) == 0: raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've", "k, bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] =", "match\") def execute(self, **kwargs): raise Exception(\"Should not be called\") def", "@property def short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self)", "return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs", "for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r # The", "issues a bit earlier. It just # keeps track of", "self.interface.inputs: raise ValueError(f\"Received unexpected keyword argument {k}\") if isinstance(v, Promise):", "FlyteValidationException(f\"Input {input_name} has already been specified for wf {self.name}.\") self._python_interface", "isinstance(input_value, list): input_promises = [] for x in input_value: input_promises.extend(get_input_values(x))", "workflow function may return a task that doesn't return anything", "@property def nodes(self) -> List[Node]: return self._compilation_state.nodes @property def inputs(self)", "def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0 else:", "self._python_interface.outputs: raise FlyteValidationException(f\"Output {output_name} already exists in workflow {self.name}\") if", "filling in the necessary inputs. \"\"\" entity_kwargs = {} for", "here has to match what 1) what the workflow would've", "!= WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ): raise FlyteValidationException(f\"Failure policy", "workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) workflow_instance = PythonFunctionWorkflow( fn, metadata=workflow_metadata, default_metadata=workflow_metadata_defaults )", "Compilation is done a bit at a time, one task", "is being called as part of a parent's workflow local", "val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output( self, output_name: str,", "transform_interface_to_typed_interface(python_interface) self._inputs = {} self._unbound_inputs = set() self._nodes = []", "python type for wf output {output_name} from Promise provided {python_type}\")", "Iterate through the workflow outputs bindings = [] output_names =", "name: str, version: str, ) -> Callable[[Callable[..., Any]], ReferenceWorkflow]: \"\"\"", "promises coming from the tasks into Promises that match the", "class ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] =", "i, _ in enumerate(function_outputs)} # Basically we need to repackage", "if isinstance(input_value, list): input_promises = [] for x in input_value:", "execute inside _local_execute. This makes mocking cleaner. \"\"\" return self._workflow_function(**kwargs)", "for b in self.output_bindings]) def add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase],", "and filling in the necessary inputs. \"\"\" entity_kwargs = {}", "t1() # or it may not return at all #", "( f\"WorkflowBase - {self._name} && \" f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} &&", "maybe key off of the name instead of value? all_input_values", "== 0: raise FlyteValueException(results, f\"{results} received but should've been VoidPromise", "with the :py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that", "Optional[WorkflowMetadataDefaults], ): name = f\"{workflow_function.__module__}.{workflow_function.__name__}\" self._workflow_function = workflow_function native_interface =", "ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all", "ImperativeWorkflow(WorkflowBase): def __init__( self, name: str, failure_policy: Optional[WorkflowFailurePolicy] = None,", "each node. intermediate_node_outputs = {GLOBAL_START_NODE: {}} # type: Dict[Node, Dict[str,", "AssertionError( \"Outputs specification for Workflow does not define a tuple,", "store state. This loop adds Tasks that are defined within", "x: isinstance(x, Promise), all_input_values): if input_value in self._unbound_inputs: self._unbound_inputs.remove(input_value) return", "arguments, which are specified using the bindings list, and a", "users from specifying inputs # as direct scalars, which means", "WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {}", "def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible)", "is None or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow", "that all nodes and workflow i/o changes were done with", "previous node. \"\"\" if not self.ready(): raise FlyteValidationException(f\"Workflow not ready,", "not be in launchplan only? # This can be in", "global start node. \"\"\" return self._inputs def __repr__(self): return super().__repr__()", "registration time the interface provided causes an issue with compilation,", "\"\"\" ctx = FlyteContextManager.current_context() self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes =", "mimics a 'closure' in the traditional sense of the word.", "first for a high-level understanding of what workflows are in", "inputs. \"\"\" entity_kwargs = {} for b in bindings: entity_kwargs[b.var]", "return case. # A workflow function may return a task", "condition is compilation. if ctx.compilation_state is not None: return create_and_link_node(ctx,", "input_value in filter(lambda x: isinstance(x, Promise), all_input_values): if input_value in", "this workflow (self) is being called as part of a", "whereas WorkflowMetadata represents metadata about the workflow itself. \"\"\" interruptible:", "as a proxy. if self.python_interface.output_tuple_name and isinstance(function_outputs, tuple): wf_outputs_as_map =", "WorkflowMetadata represents metadata about the workflow itself. \"\"\" interruptible: bool", "VoidPromise or None.\" ) expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) ==", "raise Exception(\"Can't already be compiling\") with FlyteContextManager.with_context(ctx.with_compilation_state(self.compilation_state)) as ctx: n", "return f\"{self.name}.{t.__module__}.{t.name}\" def compile(self, **kwargs): \"\"\" Supply static Python native", "self._input_parameters = transform_inputs_to_parameters(ctx, self.python_interface) all_nodes = [] prefix = f\"{ctx.compilation_state.prefix}-{self.short_name}-\"", "The task resolver interface itself is # more or less", "_local_execute(self, ctx: FlyteContext, **kwargs) -> Union[Tuple[Promise], Promise, VoidPromise]: # This", "function_outputs = self.execute(**kwargs) # First handle the empty return case.", "construct is just here to help workflow authors detect issues", "LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime you add an", "from (ClassStorageTaskResolver) # does store state. This loop adds Tasks", "self._inputs[input_name] = Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) self._unbound_inputs.add(self._inputs[input_name]) return self._inputs[input_name] def add_workflow_output(", "-> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]: return", "call pattern for Tasks. For local execution, it goes __call__", "_local_execute too for k, v in input_kwargs.items(): if k not", "ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate new promises that", ":py:func:`@workflow <flytekit.workflow>` decorator. Please see notes on that object for", "flow between tasks. Unlike a task, the function body of", "if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure != WorkflowFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ):", "That is, we force the user to declare entities already", "value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda x: isinstance(x,", "def __repr__(self): return ( f\"WorkflowBase - {self._name} && \" f\"Inputs", "execute, different things happen for the two Workflow styles. For", "part of a parent's workflow local run. # The context", "track of its own compilation state. \"\"\" return self._compilation_state @property", "raise FlyteValueException( function_outputs, f\"{function_outputs} received but should've been VoidPromise or", "be bound. \"\"\" # circular import from flytekit.core.node_creation import create_node", "inputs } def get_promise(binding_data: _literal_models.BindingData, outputs_cache: Dict[Node, Dict[str, Promise]]) ->", "received but interface has {len(self.python_interface.outputs)} outputs.\", ) return VoidPromise(self.name) #", "workflow # object itself. for n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity,", "future-proofing get_all_tasks function notwithstanding). However the # implementation of the", "pattern for Tasks. For local execution, it goes __call__ ->", "self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just a normal single element", "functionally, and 2) what a user would return in mock", "name: str, failure_policy: Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False,", "= [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return", "isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local execution expected", "task {n.flyte_entity.name}\") self.add(n.flyte_entity) # Iterate through the workflow outputs bindings", "f\"Different lengths {results} {expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]]", "input_name: str, python_type: Type) -> Interface: \"\"\" Adds an input", "-> str: return self._name @property def short_name(self) -> str: return", "def __post_init__(self): if ( self.on_failure != WorkflowFailurePolicy.FAIL_IMMEDIATELY and self.on_failure !=", "{type(binding_data.promise)} found\" ) # b.var is the name of the", "element then we return a single element if len(self.output_bindings) ==", "workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state = CompilationState(prefix=\"\") self._inputs = {} #", "workflow_function native_interface = transform_signature_to_interface(inspect.signature(workflow_function)) # TODO do we need this", "added using the add_entity function, all inputs to that entity", "if you want them to be used in the compilation.", "# This is done to support the invariant that Workflow", "-> Interface: return self._python_interface @property def interface(self) -> _interface_models.TypedInterface: return", "workflow_outputs, t, ) bindings.append(b) elif len(output_names) > 1: if not", "is not None: literals = {} for k, bd in", "each node is run one at a time. \"\"\" if", "can just iterate through the nodes in order and we", "require, # and then fill them in using the node", "workflow level outputs the same way as any other previous", "to keep track of its own compilation state. \"\"\" return", "be returned. \"\"\" def __init__( self, project: str, domain: str,", "is evaluated at serialization-time (aka compile-time). This is because while", "Admin, which is why the user is asked to provide", "the workflow's # interface. We do that by extracting out", "may return a task that doesn't return anything # def", "one output might be a list. We don't want to", "for the ImperativeWorkflow, each node is run one at a", "expected_output_names] return create_task_output(new_promises, self.python_interface) class ImperativeWorkflow(WorkflowBase): def __init__( self, name:", "\"\"\" This function is here only to try to streamline", "b.var is the name of the input to the task", "received but should've been VoidPromise or None.\") # if there's", "or not tasks launched from this workflow are by default", "else: raise Exception(f\"Workflow local execution expected 0 outputs but something", "not self.ready(): raise FlyteValidationException(f\"Workflow not ready, wf is currently {self}\")", "Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of what", "check, we just raise an Exception here. if len(entity.python_interface.outputs) ==", "fill in workflow level outputs the same way as any", "{expected_output_names}\") for idx, r in enumerate(results): intermediate_node_outputs[node][expected_output_names[idx]] = r #", "PythonFunctionWorkflow(WorkflowBase, ClassStorageTaskResolver): \"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level", "we should've already returned in the above check, we just", "None or isinstance(result, VoidPromise): return None else: raise Exception(f\"Workflow local", "detect issues a bit earlier. It just # keeps track", "for k, v in input_kwargs.items(): if k not in self.interface.inputs:", "# named tuple if self.python_interface.output_tuple_name: return (get_promise(self.output_bindings[0].binding, intermediate_node_outputs),) # Just", "list): input_promises = [] for x in input_value: input_promises.extend(get_input_values(x)) return", "List, Optional, Tuple, Type, Union from flytekit.common import constants as", "# We are already in a local execution, just continue", "f\" starting with the container type (e.g. List[int]\" ) python_type", "if len(output_names) != len(workflow_outputs): raise Exception(f\"Length mismatch {len(output_names)} vs {len(workflow_outputs)}\")", "in kwargs.items(): intermediate_node_outputs[GLOBAL_START_NODE][k] = v # Next iterate through the", "tasks, whereas WorkflowMetadata represents metadata about the workflow itself. \"\"\"", "self.python_interface and self.python_interface.output_tuple_name: variables = [k for k in self.python_interface.outputs.keys()]", "will fill in the node's entity's input arguments, which are", "case. # A workflow function may return a task that", "up the promises the node's bindings require, # and then", "now we're doing it for the workflow as a whole", "a list or dict of Promises, you must specify the", "function will fill in the node's entity's input arguments, which", "the # conversion here in this loop. The reason is", "short_name(self) -> str: return self._name.split(\".\")[-1] @property def workflow_metadata(self) -> Optional[WorkflowMetadata]:", "loop adds Tasks that are defined within the body of", "and workflow i/o changes were done with the functions above,", "val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in inputs } def get_promise(binding_data: _literal_models.BindingData,", "on_failure = 1 return _workflow_model.WorkflowMetadata(on_failure=on_failure) @dataclass class WorkflowMetadataDefaults(object): \"\"\" This", "or it may not return at all # def wf():", "v, t, self.interface.inputs[k].type)) # The output of this will always", "output tracker map we have. entity = node.flyte_entity entity_kwargs =", "not match\") def execute(self, **kwargs): raise Exception(\"Should not be called\")", "the same way as any other previous node. \"\"\" if", "python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) ->", "through the function itself because the body of the function", "bd in binding_data.map.bindings.items(): p = get_promise(bd, outputs_cache) literals[k] = p.val", "below from the output have to be pulled by fulfilling", "self._unbound_inputs: self._unbound_inputs.remove(input_value) return n def add_workflow_input(self, input_name: str, python_type: Type)", "): metadata = WorkflowMetadata(on_failure=failure_policy or WorkflowFailurePolicy.FAIL_IMMEDIATELY) workflow_metadata_defaults = WorkflowMetadataDefaults(interruptible) self._compilation_state", "= _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_IMMEDIATELY FAIL_AFTER_EXECUTABLE_NODES_COMPLETE = ( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object):", "\"\"\" if binding_data.promise is not None: if not isinstance(binding_data.promise, NodeOutput):", "We are already in a local execution, just continue the", "native_types=self.python_interface.outputs, ) # Recreate new promises that use the workflow's", "were done with the functions above, which do additional checking.", "by a function and decorated with the :py:func:`@workflow <flytekit.workflow>` decorator.", "\"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) ) as comp_ctx: # Construct", "when the workflow runs on Flyte. That is, workflows should", "self._workflow_function def task_name(self, t: PythonAutoContainerTask) -> str: return f\"{self.name}.{t.__module__}.{t.name}\" def", "is a tuple\" ) workflow_outputs = workflow_outputs[0] t = self.python_interface.outputs[output_names[0]]", "bd in binding_data.collection.bindings: p = get_promise(bd, outputs_cache) literals.append(p.val) return Promise(", "Promise]: \"\"\" Local execution of imperatively defined workflows is done", "create_native_named_tuple, create_task_output, translate_inputs_to_literals, ) from flytekit.core.python_auto_container import PythonAutoContainerTask from flytekit.core.reference_entity", "check, we just raise an error here. if len(self.python_interface.outputs) ==", "re-evaluate. self._input_parameters = None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, )", "local execution, just continue the execution context return self._local_execute(ctx, **input_kwargs)", "is # more or less stateless (the future-proofing get_all_tasks function", "def get_input_values(input_value): if isinstance(input_value, list): input_promises = [] for x", "it # should be a tuple here, if it's a", "into a Promise object, using a lookup map. Please see", "Promises, we don't have to do the # conversion here", "of the global input node, i.e. the inputs to the", "things necessary to create an SdkWorkflow, except for the missing", "a wf, a user can call a sub-workflow with a", "the traditional sense of the word. \"\"\" ctx = FlyteContextManager.current_context()", "Promise): t = self.python_interface.inputs[k] kwargs[k] = Promise(var=k, val=TypeEngine.to_literal(ctx, v, t,", "ConditionalSection): raise AssertionError(\"A Conditional block (if-else) should always end with", "workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self): return self._workflow_function def task_name(self,", "a list. We don't want to # iterate through the", "Interface: \"\"\" Adds an input to the workflow. \"\"\" if", "binding_data.scalar is not None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is", "python_type: Optional[Type] = None ): \"\"\" Add an output with", "outputs - and single-length-NamedTuples are # particularly troublesome but elegant", "are stored in this map. After all nodes are run,", "ctx.compilation_state is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self))", "and represents the decorated function. :param failure_policy: Use the options", "the node's bindings require, # and then fill them in", "# return t1() # or it may not return at", "for wf {self.name}.\") self._python_interface = self._python_interface.with_inputs(extra_inputs={input_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface)", "self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save all the things", "tuple): intermediate_node_outputs[node][expected_output_names[0]] = results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if", "promises to the workflow. The nodes in these Promise objects", "input_promises = [] for _, v in input_value.items(): input_promises.extend(get_input_values(v)) return", "vs {len(workflow_outputs)}\") for i, out in enumerate(output_names): if isinstance(workflow_outputs[i], ConditionalSection):", "(self) is being called as part of a parent's workflow", "passed and represents the decorated function. :param failure_policy: Use the", "workflow itself. \"\"\" interruptible: bool def __post_init__(self): if self.interruptible is", "FlyteEntities, ) from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface,", "all the values in kwargs are Promise objects for k,", "{python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type) ctx = FlyteContext.current_context() if ctx.compilation_state is", "execution notwithstanding, it is not evaluated again when the workflow", "val=TypeEngine.to_literal(ctx, v, t, self.interface.inputs[k].type)) # The output of this will", "Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from flytekit.core.launch_plan import LaunchPlan from", "# Get default agruements and override with kwargs passed in", "is just here to help workflow authors detect issues a", "This can be in launch plan only, but is here", "None: return Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals", "return output_tuple(*nones) else: return None # We are already in", "is None: if len(self.python_interface.outputs) != 0: raise FlyteValueException( function_outputs, f\"{function_outputs}", "This little loop was added as part of the task", "point to the global start node. \"\"\" return self._inputs def", "add_entity(self, entity: Union[PythonTask, LaunchPlan, WorkflowBase], **kwargs) -> Node: \"\"\" Anytime", "object, using a lookup map. Please see get_promise_map for the", "that object for additional information. \"\"\" def __init__( self, workflow_function:", "we just raise an Exception here. if len(entity.python_interface.outputs) == 0:", "{} # This unbound inputs construct is just here to", "so let's filter for those. # There's probably a way", "it. if len(output_names) == 1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs)", "inside _local_execute too for k, v in input_kwargs.items(): if k", "to handle the fact that the wf could've been declared", "raise AssertionError(\"Only Keyword Arguments are supported for Workflow executions\") ctx", "returned in the above check, we just raise an Exception", "get_promise_map(node.bindings, intermediate_node_outputs) # Handle the calling and outputs of each", "self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs)", "is close to, but not exactly, the call pattern for", "defined by a function and decorated with the :py:func:`@workflow <flytekit.workflow>`", "inputs, if any input_kwargs = construct_input_promises([k for k in self.interface.inputs.keys()])", "{self.interruptible} invalid\") def to_flyte_model(self): return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return", "): \"\"\" This decorator declares a function to be a", "if expected_outputs == 0: if result is None or isinstance(result,", "acceptable\") def to_flyte_model(self): if self.on_failure == WorkflowFailurePolicy.FAIL_IMMEDIATELY: on_failure = 0", "high priority # Again, we're using the output_tuple_name as a", "goes __call__ -> _local_execute -> execute From execute, different things", "call to Admin, which is why the user is asked", "{result}\") if (1 < expected_outputs == len(result)) or (result is", "a promise for a workflow call, when expecting a native", "wf output {output_name} from Promise provided {python_type}\") flyte_type = TypeEngine.to_literal_type(python_type=python_type)", "see notes on that object for additional information. \"\"\" def", "None super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=default_metadata, python_interface=native_interface, ) @property def function(self):", "tasks using the data flow between tasks. Unlike a task,", "({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \" f\"Output", "t, ) bindings.append(b) elif len(output_names) > 1: if not isinstance(workflow_outputs,", "a user would return in mock function. That is, if", "return _workflow_model.WorkflowMetadataDefaults(interruptible=self.interruptible) def construct_input_promises(inputs: List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE,", "the input promises to the workflow. The nodes in these", "f\"Inputs ({len(self._python_interface.inputs)}): {self._python_interface.inputs} && \" f\"Outputs ({len(self._python_interface.outputs)}): {self._python_interface.outputs} && \"", "defaults that are handed down to a workflow's tasks, whereas", "These conditions assume that all nodes and workflow i/o changes", "raise AssertionError( f\"The Workflow specification indicates only one return value,", "repackage the promises coming from the tasks into Promises that", "pragma: no cover # Move along, nothing to assign #", "from flytekit.core.interface import ( Interface, transform_inputs_to_parameters, transform_interface_to_typed_interface, transform_signature_to_interface, ) from", "_, v in input_value.items(): input_promises.extend(get_input_values(v)) return input_promises else: return [input_value]", "task resolver change. The task resolver interface itself is #", "Optional[WorkflowFailurePolicy] = None, interruptible: Optional[bool] = False, ): \"\"\" This", "time, one task or other entity call at a time.", "options in flytekit.WorkflowFailurePolicy :param interruptible: Whether or not tasks launched", "Promises, you must specify the python_type type for {output_name}\" f\"", "inputs to the workflow. # _local_execute should've already ensured that", "create an SdkWorkflow, except for the missing project and domain", "List[str]): return { input_name: Promise(var=input_name, val=NodeOutput(node=GLOBAL_START_NODE, var=input_name)) for input_name in", "an input to the workflow. \"\"\" if input_name in self._inputs:", "the given name from the given node output. \"\"\" if", "used. The above function though will gather all the input", "None: return create_and_link_node(ctx, entity=self, interface=self.python_interface, **input_kwargs) # This condition is", "not define a tuple, but return value is a tuple\"", "with kwargs passed in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The", "wf_outputs_as_literal_dict = translate_inputs_to_literals( ctx, wf_outputs_as_map, flyte_interface_types=self.interface.outputs, native_types=self.python_interface.outputs, ) # Recreate", "{k}\") if isinstance(v, Promise): raise ValueError(f\"Received a promise for a", "has to match what 1) what the workflow would've returned", "of value? all_input_values = get_input_values(kwargs) for input_value in filter(lambda x:", "Promise]] # Start things off with the outputs of the", "yet consumed. This # is an error that Admin would", "n in comp_ctx.compilation_state.nodes: if isinstance(n.flyte_entity, PythonAutoContainerTask) and n.flyte_entity.task_resolver == self:", "of the NodeOutput type {type(binding_data.promise)} found\" ) # b.var is", "a time. \"\"\" if len(args) > 0: raise AssertionError(\"Only Keyword", "a native value for {k}\") with FlyteContextManager.with_context( ctx.with_execution_state( ctx.new_execution_state().with_params(mode=ExecutionState.Mode.LOCAL_WORKFLOW_EXECUTION) )", "\"\"\" Please read :std:ref:`flyte:divedeep-workflows` first for a high-level understanding of", "of a task by looking at the function's signature, workflows", "None: literals = {} for k, bd in binding_data.map.bindings.items(): p", "or not the workflow is in a ready state, which", "This function is here only to try to streamline the", "workflow. # _local_execute should've already ensured that all the values", "the task resolver change. The task resolver interface itself is", "in input_kwargs = self.python_interface.default_inputs_as_kwargs input_kwargs.update(kwargs) # The first condition is", "dict): input_promises = [] for _, v in input_value.items(): input_promises.extend(get_input_values(v))", "already exists in workflow {self.name}\") if python_type is None: if", "1: if isinstance(workflow_outputs, tuple): if len(workflow_outputs) != 1: raise AssertionError(", "else: # Run some sanity checks # Even though the", "entities that construct a DAG of tasks using the data", "in self.python_interface.outputs.keys()] return output_tuple(*nones) else: return None # We are", "workflow_metadata self._workflow_metadata_defaults = workflow_metadata_defaults self._python_interface = python_interface self._interface = transform_interface_to_typed_interface(python_interface)", "= results[0] else: intermediate_node_outputs[node][expected_output_names[0]] = results else: if len(results) !=", "if input_name in self._inputs: raise FlyteValidationException(f\"Input {input_name} has already been", "variables = [k for k in self.python_interface.outputs.keys()] output_tuple = collections.namedtuple(self.python_interface.output_tuple_name,", "from flytekit.core.node import Node from flytekit.core.promise import ( NodeOutput, Promise,", "Just a normal single element return get_promise(self.output_bindings[0].binding, intermediate_node_outputs) return tuple([get_promise(b.binding,", "add_workflow_output( self, output_name: str, p: Union[Promise, List[Promise], Dict[str, Promise]], python_type:", "user to declare entities already in a topological sort. To", "t_value_type=python_type ) self._output_bindings.append(b) self._python_interface = self._python_interface.with_outputs(extra_outputs={output_name: python_type}) self._interface = transform_interface_to_typed_interface(self._python_interface)", "literals = [] for bd in binding_data.collection.bindings: p = get_promise(bd,", "are by default interruptible \"\"\" def wrapper(fn): workflow_metadata = WorkflowMetadata(on_failure=failure_policy", "one at a time. \"\"\" if len(args) > 0: raise", "collection/map out of it. if len(output_names) == 1: if isinstance(workflow_outputs,", "expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here we", "level outputs the same way as any other previous node.", "The return style here has to match what 1) what", "Node: \"\"\" Anytime you add an entity, all the inputs", "function is how local execution for imperative workflows runs. Because", "the node's entity's input arguments, which are specified using the", "However the # implementation of the TaskResolverMixin that this workflow", "inputs(self) -> Dict[str, Promise]: \"\"\" This holds the input promises", "Even though the _local_execute call generally expects inputs to be", "Python object represents a workflow defined by a function and", "domain: str, name: str, version: str, ) -> Callable[[Callable[..., Any]],", "self._interface = transform_interface_to_typed_interface(self._python_interface) def add_task(self, task: PythonTask, **kwargs) -> Node:", "variables) nones = [None for _ in self.python_interface.outputs.keys()] return output_tuple(*nones)", "function is run, for the ImperativeWorkflow, each node is run", "-> CompilationState: \"\"\" Compilation is done a bit at a", "is not None else \"\" with FlyteContextManager.with_context( ctx.with_compilation_state(CompilationState(prefix=prefix, task_resolver=self)) )", "workflow_instance if _workflow_function: return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity,", "is separate is because the one output might be a", "Unlike a task, the function body of a workflow is", "binding_from_python_std( ctx, out, self.interface.outputs[out].type, workflow_outputs[i], t, ) bindings.append(b) # Save", "if isinstance(v, Promise): raise ValueError(f\"Received a promise for a workflow", "entity=self, interface=self.python_interface, **input_kwargs) # This condition is hit when this", "fact that the wf could've been declared with a typing.NamedTuple", "# Again, we're using the output_tuple_name as a proxy. if", "the workflow inputs (if any). As things are run, their", "missing project and domain self._nodes = all_nodes self._output_bindings = bindings", "return wrapper(_workflow_function) else: return wrapper class ReferenceWorkflow(ReferenceEntity, PythonFunctionWorkflow): \"\"\" A", "from enum import Enum from typing import Any, Callable, Dict,", "return self.add_entity(sub_wf, **kwargs) def ready(self) -> bool: \"\"\" This function", "return input_promises else: return [input_value] # Every time an entity", "NodeOutput): raise FlyteValidationException( f\"Binding data Promises have to be of", "of the TaskResolverMixin that this workflow class inherits from (ClassStorageTaskResolver)", "earlier. self._unbound_inputs = set() super().__init__( name=name, workflow_metadata=metadata, workflow_metadata_defaults=workflow_metadata_defaults, python_interface=Interface(), )", "{output_name}\" f\" starting with the container type (e.g. List[int]\" )", "# A workflow function may return a task that doesn't", "with the given name from the given node output. \"\"\"", "cleaner. \"\"\" return self._workflow_function(**kwargs) def workflow( _workflow_function=None, failure_policy: Optional[WorkflowFailurePolicy] =", ") expected_output_names = list(self.python_interface.outputs.keys()) if len(expected_output_names) == 1: # Here", "for wf output {output_name} from Promise provided {python_type}\") flyte_type =", "type for wf output {output_name} from Promise provided {python_type}\") flyte_type", "any). As things are run, their outputs are stored in", "\"\"\" # circular import from flytekit.core.node_creation import create_node ctx =", "Promise(var=\"placeholder\", val=_literal_models.Literal(scalar=binding_data.scalar)) elif binding_data.collection is not None: literals = []", "{self}\") # Create a map that holds the outputs of", "0: if result is None or isinstance(result, VoidPromise): return None", "( _workflow_model.WorkflowMetadata.OnFailurePolicy.FAIL_AFTER_EXECUTABLE_NODES_COMPLETE ) @dataclass class WorkflowMetadata(object): on_failure: WorkflowFailurePolicy def __post_init__(self):" ]
[ "acoustic sequence. glen: Length vector of the target sequence. blank:", "2.0 (the \"License\"); # you may not use this file", "tuple of the backward variable probabilities - beta of shape", "t in range(0, T): # for u in range(0, U", "forward variable probabilities - alpha of shape [T, U] and", "__init__(self, blank: int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss,", "U] and the log likelihood of this backward step. \"\"\"", "raise ValueError( f\"Must have a length per example. \" f\"Given", "arrays: Alphas matrix (TxU) 2d array: Betas matrix (TxU) \"\"\"", "blank] = alphas[: T - 1, :] + betas[1:, :]", "acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank,", "blank, fastemit_lambda ) ll += reg costs.append(ll) return costs, grads", "U, V+1] labels: Labels of shape [B, U] blank: Index", "- 1, U - 1, blank] for t in reversed(range(T", "1, U - 1, blank] return alphas, loglike def backward_pass(log_probs,", "labels, blank, fastemit_lambda): \"\"\" Computes the gradients of the log_probs", "- 1, blank] for u in reversed(range(U - 1)): betas[T", "backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank,", "Returns: Gradients of shape [T, U, V+1] with respect to", "the target sequence. blank: Id of the blank token. fastemit_lambda:", "Tensor of shape [T, U, V+1] labels: Labels of shape", "return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank,", "the log probability of this step occuring. Args: Args: log_probs:", "raise ValueError( \"Must have a label length per example. \"", ": {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths,", "2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens =", "the blank token. Returns: A tuple of the backward variable", "\"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths)", "# alignment[t, U - 1] = alphas[t, U - 1]", "probability \"\"\" T, U, _ = log_probs.shape grads = np.full(log_probs.shape,", "blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads", "License for the specific language governing permissions and # limitations", "name): if len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name,", "= log_probs[T - 1, U - 1, blank] for t", "backward step. \"\"\" T, U, _ = log_probs.shape betas =", "index of blank token fastemit_lambda: Float scaling factor for FastEmit", "log_probs[T - 1, U - 1, blank]) return -reg def", "= fastemit_lambda * (alphas[T - 1, U - 1] +", "- 1, U - 1]) # The above is also", "'__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5,", "torch.max(label_lengths) T, U = log_probs.shape[1:3] if T != max_T: raise", "!= max_U + 1: raise ValueError(f\"Output length mismatch! Given U:", "U] blank: Index of the blank token. Returns: A tuple", "governing permissions and # limitations under the License. import numpy", "betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def", "labels: 1D array with shape [output time steps] blank: Index", "probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2,", "log_probs[b, :t, :u, :], labels[b, : u - 1], alphas,", "+ log_probs[T - 1, U - 1, blank]) return -reg", "in reversed(range(T - 1)): betas[t, U - 1] = betas[t", "- 1, U - 1] = log_probs[T - 1, U", "transition for u, l in enumerate(labels): grads[:, u, l] =", "Given T: {T}, Expected max T from input lengths: {max_T}\")", "g reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b, :", "forward variable. betas: Tensor of shape [T, U] which represents", "without need of computing above # reg = fastemit_lambda *", "None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 -", "_assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1)", "of the forward variable alpha. Args: log_probs: Tensor of shape", "- 1] + betas[T - 1, U - 1] #", "label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32,", "the unnormalized input actications 2d arrays: Alphas matrix (TxU) 2d", "U): alphas[0, u] = alphas[0, u - 1] + log_probs[0,", "1, labels[u - 1]] for t in range(1, T): for", "OF ANY KIND, either express or implied. # See the", "tuple of the forward variable probabilities - alpha of shape", "See the License for the specific language governing permissions and", "\"\"\" Computes probability of the backward variable beta. Args: log_probs:", "to in writing, software # distributed under the License is", "t in range(1, T): for u in range(1, U): no_emit", ":, blank] = alphas[: T - 1, :] + betas[1:,", "probabilities - beta of shape [T, U] and the log", "[T, U] which represents the backward variable. labels: Labels of", "or agreed to in writing, software # distributed under the", "numpy as np import torch from torch.autograd import Function, Variable", "loglike = alphas[T - 1, U - 1] + log_probs[T", "the fastemit regularization alignments T, U, _ = log_probs.shape #", "variable probabilities - alpha of shape [T, U] and the", "labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss", "label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts)", "1] # # for t in range(0, T): # for", "# emit = alphas[t, u] + log_probs[t, u, labels[u]] +", "f\"Must have a length per example. \" f\"Given lengths dim:", "labels with <SOS> padded as blank token in the beginning.", "betas[T - 1, U - 1] = log_probs[T - 1,", "of shape [T, U, V+1] with respect to the forward", "1, vocab size] labels: 1D array with shape [output time", "1] + log_probs[T - 1, U - 1, blank]) return", "compliance with the License. # You may obtain a copy", "is equivalent to below, without need of computing above #", "- 1, U - 1] + betas[T - 1, U", "log likelihood of this backward step. \"\"\" T, U, _", "fastemit_lambda * (alphas[T - 1, U - 1] + log_probs[T", "U, _ = log_probs.shape alphas = np.zeros((T, U), dtype='f') for", "token fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\" def", ": {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs,", "1] = betas[t + 1, U - 1] + log_probs[t,", "- 1, blank] = alphas[T - 1, U - 1]", "+ log_probs[t, u - 1, labels[u - 1]] alphas[t, u]", "raise ValueError(f\"Output length mismatch! Given U: {U}, Expected max U", "blank: Index of the blank token. Returns: Gradients of shape", "not use this file except in compliance with the License.", "requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes probability", "fastemit_lambda * (alignment[T - 1, U - 1]) # The", "log probabilities (loss) and the gradients of the activation matrix.", "backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the backward variable", "log_probs[t, u, blank] emit = betas[t, u + 1] +", "u in range(0, U - 1): # emit = alphas[t,", "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. #", "Variable from torch.nn import Module def check_type(var, t, name): if", "you may not use this file except in compliance with", "with shape [output time steps] blank: Index of the blank", "fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads =", "+ log_probs[t, U - 1, blank] for u in reversed(range(U", "{log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1,", "alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit", "\"\"\" Parameters: `blank_label` (int): default 0 - label index of", "betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0] def", "log_probs[t, U - 1, blank] for u in reversed(range(U -", "+ betas[t, U - 1] # # for t in", "torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if", "@staticmethod def backward(ctx, grad_output): return ctx.grads, None, None, None, None,", "factor for FastEmit regularization. Returns: float: The negative log-likelihood 3D", "for u, l in enumerate(labels): grads[:, u, l] = alphas[:,", "\"\"\" T, U, _ = log_probs.shape betas = np.zeros((T, U),", "U): no_emit = alphas[t - 1, u] + log_probs[t -", "betas[t, U - 1] # # for t in range(0,", "to the unnormalized input actications 2d arrays: Alphas matrix (TxU)", "betas[T - 1, U - 1] # // grad to", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "the gradients of the log_probs with respect to the log", "emit # reg = fastemit_lambda * (alignment[T - 1, U", "fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda", "transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs =", "5, 3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens", ":t, :u, :], labels[b, : u - 1], alphas, betas,", "- 1, blank] return alphas, loglike def backward_pass(log_probs, labels, blank):", "\"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward =", "FastEmit regularization. \"\"\" def __init__(self, blank: int = 0, fastemit_lambda:", "f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim", "Tensor of shape [T, U, V+1] alphas: Tensor of shape", "- 1], blank, fastemit_lambda) grads[b, :t, :u, :] = g", "- 1, u, labels[u]] for t in reversed(range(T - 1)):", "factor for FastEmit regularization. \"\"\" def __init__(self, blank: int =", "betas alignment matrix reg = fastemit_lambda * (alphas[T - 1,", "!= dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs,", "of this step occuring. Args: Args: log_probs: Tensor of shape", "2d arrays: Alphas matrix (TxU) 2d array: Betas matrix (TxU)", "1] = log_probs[T - 1, U - 1, blank] for", "be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) != dim:", "u] = betas[T - 1, u + 1] + log_probs[T", "alphas = np.zeros((T, U), dtype='f') for t in range(1, T):", "for t in range(0, T): # for u in range(0,", "u - 1], alphas, betas, blank, fastemit_lambda ) ll +=", "- 1, 0, blank] for u in range(1, U): alphas[0,", "must be {}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous():", "if var.dtype is not t: raise TypeError(\"{} must be {}\".format(name,", "1, blank] for u in reversed(range(U - 1)): betas[T -", "1], alphas, betas, blank, fastemit_lambda ) ll += reg costs.append(ll)", "costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None, None, None,", "label transition for u, l in enumerate(labels): grads[:, u, l]", "alpha of shape [T, U] and the log likelihood of", "equivalent to below, without need of computing above # reg", "def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the backward", "log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T - 1, U", "labels[u]] for t in reversed(range(T - 1)): for u in", "The above is also equivalent to below, without need of", "default 0 - label index of blank token fastemit_lambda: Float", "ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths):", "+ betas[T - 1, U - 1]) # The above", "= int(flen[b]) u = int(glen[b]) + 1 ll, g, alphas,", "0 - label index of blank token fastemit_lambda: Float scaling", "with respect to the forward log probability \"\"\" T, U,", "betas[T - 1, u + 1] + log_probs[T - 1,", "costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts,", "respect to the log probability of this step occuring. Args:", "above # reg = fastemit_lambda * (alphas[T - 1, U", "this backward step. \"\"\" T, U, _ = log_probs.shape betas", "np import torch from torch.autograd import Function, Variable from torch.nn", "glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the", "= log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T - 1,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts", "ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels,", "reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def forward(ctx,", "log_probs: Tensor of shape [T, U, V+1] alphas: Tensor of", "under the License. # # Copyright 2018-2019, <NAME> # #", "{max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients", "- 1] + betas[T - 1, U - 1]) #", "<NAME> # # Licensed under the Apache License, Version 2.0", "+ 1, vocab size] labels: 1D array with shape [output", "= alphas[T - 1, U - 1] + log_probs[T -", "scaling factor for FastEmit regularization. Returns: Batch of transducer forward", "file except in compliance with the License. # You may", "2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under", "assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens,", ":] = g reg = fastemit_regularization( log_probs[b, :t, :u, :],", "{log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have", "- 1)): for u in reversed(range(U - 1)): no_emit =", "if T != max_T: raise ValueError(f\"Input length mismatch! Given T:", "= betas[T - 1, u + 1] + log_probs[T -", "forward variable. betas: Unused. Tensor of shape [T, U] which", "language governing permissions and # limitations under the License. import", "P˜(At, u|x) \"\"\" # General calculation of the fastemit regularization", "Args: log_probs: Tensor of shape [T, U, V+1] labels: Labels", "- 1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit)", "probabilities - alpha of shape [T, U] and the log", "Id of the blank token. fastemit_lambda: Float scaling factor for", "[B, U] blank: Index of the blank token. Returns: Gradients", "of the target sequence. blank: Id of the blank token.", "= log_probs.shape # alignment = np.zeros((T, U), dtype='float32') # #", "KIND, either express or implied. # See the License for", "for u in reversed(range(U - 1)): betas[T - 1, u]", "for t in reversed(range(T - 1)): for u in reversed(range(U", "1, blank] return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\"", "alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of", "= RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels", "- 1] + log_probs[0, u - 1, labels[u - 1]]", "- 1] = log_probs[T - 1, U - 1, blank]", "1)): for u in reversed(range(U - 1)): no_emit = betas[t", "(the \"License\"); # you may not use this file except", "fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization from the", "loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3)", "max_U + 1: raise ValueError(f\"Output length mismatch! Given U: {U},", "U - 1, blank] for u in reversed(range(U - 1)):", "return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs:", "u] + log_probs[t - 1, u, blank] emit = alphas[t,", "- 1]) # The above is equivalent to below, without", "[T, U, V+1] alphas: Tensor of shape [T, U] which", "computed for log_probs - please \" \"mark other tensors as", "Tensor of shape [T, U, V+1] labels: Unused. Labels of", "self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def", "alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs,", "# # Unless required by applicable law or agreed to", "variable probabilities - beta of shape [T, U] and the", "and # limitations under the License. # # Copyright 2018-2019,", "(TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas, ll_backward", ") check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\")", "1, :] + betas[1:, :] # // grad to label", "a label length per example. \" f\"Given label lengths dim", "matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank) betas,", "of this forward step. \"\"\" T, U, _ = log_probs.shape", ": {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must", "implied. # See the License for the specific language governing", "+ 1] + log_probs[T - 1, u, labels[u]] for t", "emit = alphas[t, u] + log_probs[t, u, labels[u]] + betas[t,", "blank token. Returns: Gradients of shape [T, U, V+1] with", "1, U - 1]) # The above is also equivalent", "# == alphas[T - 1, U - 1] + betas[T", "of the forward variable probabilities - alpha of shape [T,", "def check_dim(var, dim, name): if len(var.shape) != dim: raise ValueError(\"{}", "- 1, U - 1] # // grad to last", "\"\"\" T, U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\"))", "of shape [T, U] which represents the backward variable. blank:", "1] # alignment[t, u] = emit # reg = fastemit_lambda", "U: {U}, Expected max U from target lengths: {max_U} +", "occuring. Args: Args: log_probs: Tensor of shape [T, U, V+1]", "betas[t + 1, u] + log_probs[t, u, blank] emit =", "ctx.grads, None, None, None, None, None class RNNTLoss(Module): \"\"\" Parameters:", "labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation of", "variable alpha. Args: log_probs: Tensor of shape [T, U, V+1]", "alphas, betas, blank, fastemit_lambda ) ll += reg costs.append(ll) return", "ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas,", "torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if T", "== alphas[T - 1, U - 1] + betas[T -", "Returns: float: The negative log-likelihood 3D array: Gradients with respect", "- 1, blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0):", "float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda =", "costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return", "1] = alphas[t, U - 1] + betas[t, U -", "labels[b, : u - 1], blank, fastemit_lambda) grads[b, :t, :u,", "U] which represents the backward variable. labels: Labels of shape", "{U}, Expected max U from target lengths: {max_U} + 1\")", "+ log_probs[t, u, blank] emit = betas[t, u + 1]", "Returns: The regularized negative log likelihood - lambda * P˜(At,", "_RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda):", "= log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length mismatch!", "Unless required by applicable law or agreed to in writing,", "this step occuring. Args: Args: log_probs: Tensor of shape [T,", "== '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2,", "1, U - 1] grads[: T - 1, :, blank]", "+ betas[:, u + 1] grads = -np.exp(grads + log_probs", "to label transition for u, l in enumerate(labels): grads[:, u,", "the specific language governing permissions and # limitations under the", "# limitations under the License. import numpy as np import", "ground truth labels with <SOS> padded as blank token in", "RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 - label index", "dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) if", "for FastEmit regularization. Returns: The regularized negative log likelihood -", "- [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args:", "length mismatch! Given U: {U}, Expected max U from target", "step occuring. Args: Args: log_probs: Tensor of shape [T, U,", "\"Must have a label length per example. \" f\"Given label", "{label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4,", "range(0, U - 1): # emit = alphas[t, u] +", "vocab size] labels: 1D array with shape [output time steps]", "1] + log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit)", "# General calculation of the fastemit regularization alignments T, U,", "T, U, V+1]. Activation matrix normalized with log-softmax. labels: [B,", "must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): #", "[T, U, V+1] labels: Unused. Labels of shape [B, U]", "1D array with shape [output time steps] blank: Index of", "-ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0,", "1] + log_probs[t, u - 1, labels[u - 1]] alphas[t,", "blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(),", "1, u] + log_probs[t - 1, u, blank] emit =", "forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the forward variable", "return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability", "fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the batch. Args:", "token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: float:", "U), dtype='f') betas[T - 1, U - 1] = log_probs[T", "\"mark other tensors as not requiring gradients\" ) def forward_pass(log_probs,", "t: raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name):", "f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]:", "# The above is also equivalent to below, without need", "to the forward log probability \"\"\" T, U, _ =", "- 1] + log_probs[T - 1, U - 1, blank]", "transition grads[T - 1, U - 1, blank] = alphas[T", "(c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed", "token. Returns: Gradients of shape [T, U, V+1] with respect", "t in range(1, T): alphas[t, 0] = alphas[t - 1,", "of shape [B, U] alphas: Tensor of shape [T, U]", "2, 5, 3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32)", "1, U - 1] # // grad to last blank", "= alphas[0, u - 1] + log_probs[0, u - 1,", "for log_probs - please \" \"mark other tensors as not", "1, 0, blank] for u in range(1, U): alphas[0, u]", "T, U, _ = log_probs.shape alphas = np.zeros((T, U), dtype='f')", "\"\"\" Computes the gradients of the log_probs with respect to", "of the blank token. Returns: A tuple of the backward", "_ = log_probs.shape # alignment = np.zeros((T, U), dtype='float32') #", "= np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U -", "u, l] = alphas[:, u] + betas[:, u + 1]", "alphas[: T - 1, :] + betas[1:, :] # //", "labels, blank): \"\"\" Computes probability of the backward variable beta.", "u in reversed(range(U - 1)): betas[T - 1, u] =", "for u in range(1, U): no_emit = alphas[t - 1,", "# for u in range(0, U - 1): # emit", "Expected max T from input lengths: {max_T}\") if U !=", "range(1, T): for u in range(1, U): no_emit = alphas[t", "for t in reversed(range(T - 1)): betas[t, U - 1]", "not t: raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var,", "variable. betas: Tensor of shape [T, U] which represents the", "above is also equivalent to below, without need of computing", "as not requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\"", "1, U - 1, blank]) return -reg def transduce(log_probs, labels,", "[output time steps] blank: Index of the blank token. fastemit_lambda:", "range(1, T): alphas[t, 0] = alphas[t - 1, 0] +", "(alphas[T - 1, U - 1] + log_probs[T - 1,", "in range(1, U): alphas[0, u] = alphas[0, u - 1]", "torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32,", "Index of the blank token. Returns: A tuple of the", "betas = np.zeros((T, U), dtype='f') betas[T - 1, U -", "# // grad to label transition for u, l in", "Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels, blank)", "in range(0, U - 1): # emit = alphas[t, u]", "shape [B, U] alphas: Tensor of shape [T, U] which", "U from target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert", "no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels,", "You may obtain a copy of the License at #", "to below, without need of computing the betas alignment matrix", "License. import numpy as np import torch from torch.autograd import", "+ 1] + log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit,", "lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, (", "= blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self,", "- 1, 0] + log_probs[t - 1, 0, blank] for", "below, without need of computing above # reg = fastemit_lambda", "labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike =", "NVIDIA CORPORATION. All rights reserved. # # Licensed under the", "- 1] = betas[t + 1, U - 1] +", "[T, U, V+1] labels: Labels of shape [B, U] blank:", "= np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas,", "U - 1] # # for t in range(0, T):", "blank] emit = betas[t, u + 1] + log_probs[t, u,", "which represents the backward variable. labels: Labels of shape [B,", "fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens, label_lens):", "alphas[t, 0] = alphas[t - 1, 0] + log_probs[t -", "+ 1: raise ValueError(f\"Output length mismatch! Given U: {U}, Expected", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "None, None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int):", "[B, U] alphas: Tensor of shape [T, U] which represents", "calculation of the fastemit regularization alignments T, U, _ =", ") def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the", "gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of", "grads[:, u, l] = alphas[:, u] + betas[:, u +", "alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T - 1,", "U] and the log likelihood of this forward step. \"\"\"", "blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape [input", "transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with", "Returns: Batch of transducer forward log probabilities (loss) and the", "Computes probability of the backward variable beta. Args: log_probs: Tensor", "t in reversed(range(T - 1)): betas[t, U - 1] =", "- 1] + log_probs[T - 1, U - 1, blank])", "betas[t, u + 1] + log_probs[t, u, labels[u]] betas[t, u]", "1, blank] = alphas[T - 1, U - 1] grads[:", "u in reversed(range(U - 1)): no_emit = betas[t + 1,", "log_probs with respect to the log probability of this step", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "the blank token. Returns: Gradients of shape [T, U, V+1]", "License. # You may obtain a copy of the License", "* P˜(At, u|x) \"\"\" # General calculation of the fastemit", "# check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\")", "FastEmit regularization. Returns: Batch of transducer forward log probabilities (loss)", ":], labels[b, : u - 1], blank, fastemit_lambda) grads[b, :t,", "return costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None, None,", "# Copyright 2018-2019, <NAME> # # Licensed under the Apache", "# The above is equivalent to below, without need of", "import Function, Variable from torch.nn import Module def check_type(var, t,", "padded as blank token in the beginning. flen: Length vector", "+ log_probs[t, u, labels[u]] + betas[t, u + 1] #", "RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels =", "the batch. Args: log_probs: [B, T, U, V+1]. Activation matrix", "-np.exp(grads + log_probs - log_like) if fastemit_lambda > 0.0: for", "of the acoustic sequence. glen: Length vector of the target", "1, blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\"", "= g reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b,", "3) labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens =", "int(flen[b]) u = int(glen[b]) + 1 ll, g, alphas, betas", "- label index of blank token fastemit_lambda: Float scaling factor", "1, U - 1] + log_probs[T - 1, U -", "U] which represents the forward variable. betas: Unused. Tensor of", "blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization from", "u in range(1, U): no_emit = alphas[t - 1, u]", "act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads =", "variable. blank: Index of the blank token. fastemit_lambda: Float scaling", "\"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\")", "Args: log_probs: 3D array with shape [input len, output len", "if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var,", "1, U - 1, blank] = alphas[T - 1, U", "- lambda * P˜(At, u|x) \"\"\" # General calculation of", "- 1] + log_probs[t, U - 1, blank] for u", "shape [T, U, V+1] with respect to the forward log", "if U != max_U + 1: raise ValueError(f\"Output length mismatch!", "u - 1] + log_probs[t, u - 1, labels[u -", "V+1]. Activation matrix normalized with log-softmax. labels: [B, U+1] -", "+ log_probs[T - 1, u, labels[u]] for t in reversed(range(T", "u - 1], blank, fastemit_lambda) grads[b, :t, :u, :] =", "in range(0, T): # for u in range(0, U -", "= grads return costs @staticmethod def backward(ctx, grad_output): return ctx.grads,", "tensor.requires_grad, ( \"gradients only computed for log_probs - please \"", "- 1] # // grad to last blank transition grads[T", "\"\"\" def __init__(self, blank: int = 0, fastemit_lambda: float =", "0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes", "- 1] = alphas[t, U - 1] + betas[t, U", "torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod", "import Module def check_type(var, t, name): if var.dtype is not", "- 1] grads[: T - 1, :, blank] = alphas[:", "[T, U] and the log likelihood of this forward step.", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "[B, T, U, V+1]. Activation matrix normalized with log-softmax. labels:", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "_ = log_probs.shape alphas = np.zeros((T, U), dtype='f') for t", "U - 1, blank] return alphas, loglike def backward_pass(log_probs, labels,", "label length per example. \" f\"Given label lengths dim :", "+ log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return", "log_probs - please \" \"mark other tensors as not requiring", "np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]): t =", "language governing permissions and # limitations under the License. #", "the backward variable. blank: Index of the blank token. fastemit_lambda:", "from target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not", "required by applicable law or agreed to in writing, software", "if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a label", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "= torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32)", "of the blank token. Returns: Gradients of shape [T, U,", "represents the backward variable. blank: Index of the blank token.", "length mismatch! Given T: {T}, Expected max T from input", "for u in range(0, U - 1): # emit =", "name): if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def", "Float scaling factor for FastEmit regularization. \"\"\" def __init__(self, blank:", "agreed to in writing, software # distributed under the License", "range(0, T): # alignment[t, U - 1] = alphas[t, U", "factor for FastEmit regularization. Returns: Batch of transducer forward log", "betas[:, u + 1] grads = -np.exp(grads + log_probs -", "U - 1] = alphas[t, U - 1] + betas[t,", "distributed under the License is distributed on an \"AS IS\"", "_RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) ==", "U, V+1] with respect to the forward log probability \"\"\"", "log_like = betas[0, 0] # == alphas[T - 1, U", "@staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs,", ":] # // grad to label transition for u, l", "no_emit = alphas[t - 1, u] + log_probs[t - 1,", "log_probs: 3D array with shape [input len, output len +", "\"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must", "acts, labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens)", "label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels,", "= log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0]", ":] + betas[1:, :] # // grad to label transition", "beta of shape [T, U] and the log likelihood of", "check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs,", "Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U,", "\"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U =", "\"\"\" Compute the transducer loss of the batch. Args: log_probs:", "# alignment = np.zeros((T, U), dtype='float32') # # for t", "reversed(range(T - 1)): betas[t, U - 1] = betas[t +", "log likelihood of this forward step. \"\"\" T, U, _", "1], blank, fastemit_lambda) grads[b, :t, :u, :] = g reg", "of the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs =", "= fastemit_lambda * (alignment[T - 1, U - 1]) #", "- 1] + betas[t, U - 1] # # for", "Tensor of shape [T, U] which represents the backward variable.", "betas, blank, fastemit_lambda ) ll += reg costs.append(ll) return costs,", "== 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts", "- 1, U - 1, blank] return alphas, loglike def", "of the backward variable probabilities - beta of shape [T,", "u + 1] # alignment[t, u] = emit # reg", "name): if var.dtype is not t: raise TypeError(\"{} must be", "3D array with shape [input len, output len + 1,", "l in enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda)", "None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default", "raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name): if", "1] + betas[t, U - 1] # # for t", "FastEmit regularization. Returns: The regularized negative log likelihood - lambda", "label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim :", "OR CONDITIONS OF ANY KIND, either express or implied. #", "= betas[0, 0] # == alphas[T - 1, U -", "the License is distributed on an \"AS IS\" BASIS, #", "must be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) !=", "u in range(1, U): alphas[0, u] = alphas[0, u -", "act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(),", "labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape", "0.0: for u, l in enumerate(labels): grads[:, u, l] =", "under the License. import numpy as np import torch from", "of this backward step. \"\"\" T, U, _ = log_probs.shape", "actications 2d arrays: Alphas matrix (TxU) 2d array: Betas matrix", "blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs,", "the forward variable. betas: Tensor of shape [T, U] which", "forward step. \"\"\" T, U, _ = log_probs.shape alphas =", "- ground truth labels with <SOS> padded as blank token", "betas[T - 1, u] = betas[T - 1, u +", "law or agreed to in writing, software # distributed under", "= int(glen[b]) + 1 ll, g, alphas, betas = transduce(log_probs[b,", "vector of the target sequence. blank: Id of the blank", "fastemit_lambda) * grads[:, u, l] return grads def fastemit_regularization(log_probs, labels,", "Expected max U from target lengths: {max_U} + 1\") def", "alpha. Args: log_probs: Tensor of shape [T, U, V+1] labels:", "alphas[t, U - 1] + betas[t, U - 1] #", "with respect to the unnormalized input actications 2d arrays: Alphas", "Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # #", ") if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a", "other tensors as not requiring gradients\" ) def forward_pass(log_probs, labels,", "def check_type(var, t, name): if var.dtype is not t: raise", "may obtain a copy of the License at # #", "the gradients of the activation matrix. \"\"\" grads = np.zeros_like(log_probs)", "log_probs[t, u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas,", "[T, U] which represents the forward variable. betas: Tensor of", "log_probs[t, u, labels[u]] + betas[t, u + 1] # alignment[t,", "Function, Variable from torch.nn import Module def check_type(var, t, name):", "may not use this file except in compliance with the", "+ betas[1:, :] # // grad to label transition for", "Activation matrix normalized with log-softmax. labels: [B, U+1] - ground", "batch. Args: log_probs: [B, T, U, V+1]. Activation matrix normalized", "- 1, U - 1] grads[: T - 1, :,", "this file except in compliance with the License. # You", "_assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed for log_probs", "# # Licensed under the Apache License, Version 2.0 (the", "+= reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod def", "blank, fastemit_lambda): \"\"\" Computes the gradients of the log_probs with", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "1] grads[: T - 1, :, blank] = alphas[: T", "Length vector of the target sequence. blank: Id of the", "alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, : u", "reversed(range(U - 1)): no_emit = betas[t + 1, u] +", "class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank,", "\"\"\" grads = np.zeros_like(log_probs) costs = [] for b in", "\"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\")", "1]) # The above is also equivalent to below, without", "mismatch! Given U: {U}, Expected max U from target lengths:", "Returns: A tuple of the backward variable probabilities - beta", "- 1, blank] for t in reversed(range(T - 1)): betas[t,", "check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T,", "-reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D", "blank: Index of the blank token. fastemit_lambda: Float scaling factor", "= transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs", "- alpha of shape [T, U] and the log likelihood", "labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss", "U), dtype='float32') # # for t in range(0, T): #", "the forward variable. betas: Unused. Tensor of shape [T, U]", "shape [T, U] and the log likelihood of this forward", "array: Gradients with respect to the unnormalized input actications 2d", "+ log_probs - log_like) if fastemit_lambda > 0.0: for u,", "U - 1]) # The above is equivalent to below,", "ValueError(f\"Output length mismatch! Given U: {U}, Expected max U from", "torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2, 1, 2]],", "factor for FastEmit regularization. Returns: The regularized negative log likelihood", "U - 1, blank]) return -reg def transduce(log_probs, labels, blank=0,", "__name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts = torch.randn(1,", "also equivalent to below, without need of computing the betas", "= torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda)", "example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim", "per example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs", "log-softmax. labels: [B, U+1] - ground truth labels with <SOS>", "T: {T}, Expected max T from input lengths: {max_T}\") if", "or implied. # See the License for the specific language", "the log likelihood of this backward step. \"\"\" T, U,", "torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def backward(ctx, grad_output):", "blank] = alphas[T - 1, U - 1] grads[: T", "T, U, _ = log_probs.shape betas = np.zeros((T, U), dtype='f')", "in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) + 1", "1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike", "regularization alignments T, U, _ = log_probs.shape # alignment =", "negative log-likelihood 3D array: Gradients with respect to the unnormalized", "labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda)", "alphas[t, u - 1] + log_probs[t, u - 1, labels[u", "grads[: T - 1, :, blank] = alphas[: T -", "\"\"\" Args: log_probs: 3D array with shape [input len, output", "u + 1] + log_probs[t, u, labels[u]] betas[t, u] =", "> 0.0: for u, l in enumerate(labels): grads[:, u, l]", "- 1] # # for t in range(0, T): #", "ll += reg costs.append(ll) return costs, grads class _RNNT(Function): @staticmethod", "alphas[T - 1, U - 1] + betas[T - 1,", "for u in reversed(range(U - 1)): no_emit = betas[t +", "2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T =", "the forward variable alpha. Args: log_probs: Tensor of shape [T,", "T - 1, :, blank] = alphas[: T - 1,", "scaling factor for FastEmit regularization. \"\"\" def __init__(self, blank: int", "torch.manual_seed(0) acts = torch.randn(1, 2, 5, 3) labels = torch.tensor([[0,", "log_probs.shape alphas = np.zeros((T, U), dtype='f') for t in range(1,", "Module def check_type(var, t, name): if var.dtype is not t:", "np.zeros((T, U), dtype='float32') # # for t in range(0, T):", "1)): betas[T - 1, u] = betas[T - 1, u", "{}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{}", "have a length per example. \" f\"Given lengths dim: {lengths.shape[0]},", "last blank transition grads[T - 1, U - 1, blank]", "!= log_probs.shape[0]: raise ValueError( \"Must have a label length per", "var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name):", "grads[b, :t, :u, :] = g reg = fastemit_regularization( log_probs[b,", "\" f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\")", "U, V+1] alphas: Tensor of shape [T, U] which represents", "- 1, U - 1, blank] = alphas[T - 1,", "_ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0,", "All rights reserved. # # Licensed under the Apache License,", "l] = alphas[:, u] + betas[:, u + 1] grads", "u, l in enumerate(labels): grads[:, u, l] = (1.0 +", "np.zeros((T, U), dtype='f') betas[T - 1, U - 1] =", "\"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths)", "u, l] return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank,", "grads return costs @staticmethod def backward(ctx, grad_output): return ctx.grads, None,", "ValueError( \"Must have a label length per example. \" f\"Given", "FastEmit regularization. Returns: float: The negative log-likelihood 3D array: Gradients", "= transduce(log_probs[b, :t, :u, :], labels[b, : u - 1],", "please \" \"mark other tensors as not requiring gradients\" )", "fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: The regularized", "= alphas[:, u] + betas[:, u + 1] grads =", "costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens,", "(TxU) 2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward =", "compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas,", "self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply", "sequence. glen: Length vector of the target sequence. blank: Id", "- 1, u + 1] + log_probs[T - 1, u,", "l] return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda):", "backward variable. labels: Labels of shape [B, U] blank: Index", "- 1)): betas[t, U - 1] = betas[t + 1,", "grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes", "1]) # The above is equivalent to below, without need", "label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(),", "[B, U+1] - ground truth labels with <SOS> padded as", "in writing, software # distributed under the License is distributed", "governing permissions and # limitations under the License. # #", "dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\")", "matrix normalized with log-softmax. labels: [B, U+1] - ground truth", "vector of the acoustic sequence. glen: Length vector of the", "for t in range(1, T): for u in range(1, U):", "transducer loss of the batch. Args: log_probs: [B, T, U,", "from input lengths: {max_T}\") if U != max_U + 1:", "alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\"", "grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # ==", "+ log_probs[0, u - 1, labels[u - 1]] for t", "enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:,", "for t in range(1, T): alphas[t, 0] = alphas[t -", "Args: Args: log_probs: Tensor of shape [T, U, V+1] alphas:", "def forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads", "[T, U, V+1] with respect to the forward log probability", "_ = log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T -", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "permissions and # limitations under the License. # # Copyright", "token. Returns: A tuple of the backward variable probabilities -", "License, Version 2.0 (the \"License\"); # you may not use", "forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels)", "label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts, labels, act_lens, label_lens)", "log_probs.shape # alignment = np.zeros((T, U), dtype='float32') # # for", "+ 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only", "+ 1] grads = -np.exp(grads + log_probs - log_like) if", "= alphas[t, u - 1] + log_probs[t, u - 1,", "the paper - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission", "paper - [FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148)", "None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0", "log_probs[T - 1, U - 1, blank] for t in", "of the log_probs with respect to the log probability of", "the License for the specific language governing permissions and #", "= _RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size())", "shape [T, U] which represents the backward variable. blank: Index", "[T, U] and the log likelihood of this backward step.", "2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts =", "raise TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name): if", "def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the", "1, u, blank] emit = alphas[t, u - 1] +", "labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)]) grads", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise ValueError(", "2018-2019, <NAME> # # Licensed under the Apache License, Version", "forward(ctx, acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads =", "alphas[T - 1, U - 1] grads[: T - 1,", "in range(0, T): # alignment[t, U - 1] = alphas[t,", "- beta of shape [T, U] and the log likelihood", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "blank] for t in reversed(range(T - 1)): betas[t, U -", "T - 1, :] + betas[1:, :] # // grad", "grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0):", "log_like) if fastemit_lambda > 0.0: for u, l in enumerate(labels):", "Args: log_probs: [B, T, U, V+1]. Activation matrix normalized with", "- 1): # emit = alphas[t, u] + log_probs[t, u,", "1, u, labels[u]] for t in reversed(range(T - 1)): for", "Gradients of shape [T, U, V+1] with respect to the", "scaling factor for FastEmit regularization. Returns: The regularized negative log", "the transducer loss of the batch. Args: log_probs: [B, T,", "array with shape [output time steps] blank: Index of the", "this forward step. \"\"\" T, U, _ = log_probs.shape alphas", "4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1,", "fastemit_lambda * (alphas[T - 1, U - 1] + betas[T", "l] = (1.0 + fastemit_lambda) * grads[:, u, l] return", "labels, act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens)", "dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels,", "ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b,", "General calculation of the fastemit regularization alignments T, U, _", "# distributed under the License is distributed on an \"AS", "to below, without need of computing above # reg =", "# Unless required by applicable law or agreed to in", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "1\") def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed", "T, U = log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input", "regularized negative log likelihood - lambda * P˜(At, u|x) \"\"\"", "alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients of", "U] which represents the backward variable. blank: Index of the", "- 1, u] + log_probs[t - 1, u, blank] emit", "reversed(range(U - 1)): betas[T - 1, u] = betas[T -", "which represents the backward variable. blank: Index of the blank", "1] + log_probs[t, U - 1, blank] for u in", "in reversed(range(U - 1)): no_emit = betas[t + 1, u]", "U] which represents the forward variable. betas: Tensor of shape", "T, U, _ = log_probs.shape # alignment = np.zeros((T, U),", "betas, ll_backward = backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas,", "grads[:, u, l] return grads def fastemit_regularization(log_probs, labels, alphas, betas,", "blank]) return -reg def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args:", "dtype='f') for t in range(1, T): alphas[t, 0] = alphas[t", "the Apache License, Version 2.0 (the \"License\"); # you may", "label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens, label_lens,", "t in reversed(range(T - 1)): for u in reversed(range(U -", "= alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u", "1 ll, g, alphas, betas = transduce(log_probs[b, :t, :u, :],", "shape [input len, output len + 1, vocab size] labels:", "= alphas[: T - 1, :] + betas[1:, :] #", "u - 1] + log_probs[0, u - 1, labels[u -", "not tensor.requires_grad, ( \"gradients only computed for log_probs - please", "= torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts,", "limitations under the License. import numpy as np import torch", "dim, name): if len(var.shape) != dim: raise ValueError(\"{} must be", "!= max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected", "represents the backward variable. labels: Labels of shape [B, U]", "loss of the batch. Args: log_probs: [B, T, U, V+1].", "U - 1] + betas[T - 1, U - 1]", "= np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # == alphas[T", "U - 1] + log_probs[t, U - 1, blank] for", "= -np.exp(grads + log_probs - log_like) if fastemit_lambda > 0.0:", "self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels,", "dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val", "* (alphas[T - 1, U - 1] + log_probs[T -", "blank: int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__()", "Gradients with respect to the unnormalized input actications 2d arrays:", "log-likelihood 3D array: Gradients with respect to the unnormalized input", "in range(1, U): no_emit = alphas[t - 1, u] +", "u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs,", "# reg = fastemit_lambda * (alphas[T - 1, U -", "acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, ) costs = torch.FloatTensor([sum(costs)])", "check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]:", "torch.autograd import Function, Variable from torch.nn import Module def check_type(var,", "U = log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length", "range(0, T): # for u in range(0, U - 1):", "check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name))", "blank token. Returns: A tuple of the forward variable probabilities", "log_probs - log_like) if fastemit_lambda > 0.0: for u, l", "under the License is distributed on an \"AS IS\" BASIS,", "+ 1] # alignment[t, u] = emit # reg =", "fastemit_lambda ) ll += reg costs.append(ll) return costs, grads class", "transduce(log_probs[b, :t, :u, :], labels[b, : u - 1], blank,", "grad_output): return ctx.grads, None, None, None, None, None class RNNTLoss(Module):", "to the log probability of this step occuring. Args: Args:", "U - 1] + betas[t, U - 1] # #", "grads[T - 1, U - 1, blank] = alphas[T -", "log_probs.shape[1:3] if T != max_T: raise ValueError(f\"Input length mismatch! Given", "= np.zeros((T, U), dtype='float32') # # for t in range(0,", "[T, U] which represents the forward variable. betas: Unused. Tensor", ": u - 1], alphas, betas, blank, fastemit_lambda ) ll", "in reversed(range(T - 1)): for u in reversed(range(U - 1)):", "mismatch! Given T: {T}, Expected max T from input lengths:", ":u, :], labels[b, : u - 1], blank, fastemit_lambda) grads[b,", "the acoustic sequence. glen: Length vector of the target sequence.", "emit = betas[t, u + 1] + log_probs[t, u, labels[u]]", "+ log_probs[T - 1, U - 1, blank] return alphas,", "t in range(0, T): # alignment[t, U - 1] =", "computing the betas alignment matrix reg = fastemit_lambda * (alphas[T", "alignments T, U, _ = log_probs.shape # alignment = np.zeros((T,", "log_probs: [B, T, U, V+1]. Activation matrix normalized with log-softmax.", "a length per example. \" f\"Given lengths dim: {lengths.shape[0]}, \"", "blank: Index of the blank token. Returns: A tuple of", "the blank token. Returns: A tuple of the forward variable", "\"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels,", "- please \" \"mark other tensors as not requiring gradients\"", "-1) return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__", "no_emit = betas[t + 1, u] + log_probs[t, u, blank]", "ctx.grads = grads return costs @staticmethod def backward(ctx, grad_output): return", "example. \" f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log", "backward variable beta. Args: log_probs: Tensor of shape [T, U,", "from torch.autograd import Function, Variable from torch.nn import Module def", "lambda * P˜(At, u|x) \"\"\" # General calculation of the", "Returns: A tuple of the forward variable probabilities - alpha", "U - 1]) # The above is also equivalent to", "for FastEmit regularization. Returns: float: The negative log-likelihood 3D array:", "u, labels[u]] + betas[t, u + 1] # alignment[t, u]", "Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U, V+1]", "alphas[T - 1, U - 1] + log_probs[T - 1,", "raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max T", "max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if T !=", "U, _ = log_probs.shape betas = np.zeros((T, U), dtype='f') betas[T", "- 1, U - 1]) # The above is equivalent", "fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank,", "ANY KIND, either express or implied. # See the License", "lengths dim : {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\"", "the License. # You may obtain a copy of the", "of FastEmit regularization from the paper - [FastEmit: Low-latency Streaming", "def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the", "# for t in range(0, T): # alignment[t, U -", "# See the License for the specific language governing permissions", "T): # alignment[t, U - 1] = alphas[t, U -", "T): alphas[t, 0] = alphas[t - 1, 0] + log_probs[t", "_assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return", "betas: Tensor of shape [T, U] which represents the backward", "to last blank transition grads[T - 1, U - 1,", "check_dim(var, dim, name): if len(var.shape) != dim: raise ValueError(\"{} must", "Length vector of the acoustic sequence. glen: Length vector of", "blank) grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return", "- 1, u, blank] emit = alphas[t, u - 1]", "(1.0 + fastemit_lambda) * grads[:, u, l] return grads def", "grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda, )", "activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs = [] for", "be {}\".format(name, t)) def check_contiguous(var, name): if not var.is_contiguous(): raise", "labels, blank): \"\"\" Computes probability of the forward variable alpha.", "probability of the backward variable beta. Args: log_probs: Tensor of", "labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs,", "array with shape [input len, output len + 1, vocab", "U - 1, blank] for t in reversed(range(T - 1)):", "1] + betas[T - 1, U - 1]) # The", "A tuple of the backward variable probabilities - beta of", "reg = fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u", "permissions and # limitations under the License. import numpy as", "b in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) +", "1, u] + log_probs[t, u, blank] emit = betas[t, u", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "import numpy as np import torch from torch.autograd import Function,", "A tuple of the forward variable probabilities - alpha of", "writing, software # distributed under the License is distributed on", "labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels,", "Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor", "= torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs", "range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b]) + 1 ll,", "loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes probability of the", "fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array with shape [input len,", "of the blank token. Returns: A tuple of the forward", "fastemit_lambda): \"\"\" Computes the gradients of the log_probs with respect", "as blank token in the beginning. flen: Length vector of", "U, _ = log_probs.shape # alignment = np.zeros((T, U), dtype='float32')", "return self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ ==", "g, alphas, betas = transduce(log_probs[b, :t, :u, :], labels[b, :", "\"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\")", "License. # # Copyright 2018-2019, <NAME> # # Licensed under", "_assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts,", "var.dtype is not t: raise TypeError(\"{} must be {}\".format(name, t))", "max U from target lengths: {max_U} + 1\") def _assert_no_grad(tensor):", "shape [T, U] which represents the backward variable. labels: Labels", "T from input lengths: {max_T}\") if U != max_U +", "def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must be", "( \"gradients only computed for log_probs - please \" \"mark", "represents the forward variable. betas: Tensor of shape [T, U]", "Unused. Tensor of shape [T, U] which represents the backward", "ValueError( f\"Must have a length per example. \" f\"Given lengths", "torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\")", "1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U =", "token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: Batch", "1)): betas[t, U - 1] = betas[t + 1, U", ": u - 1], blank, fastemit_lambda) grads[b, :t, :u, :]", "= np.zeros((T, U), dtype='f') for t in range(1, T): alphas[t,", "u] + log_probs[t, u, blank] emit = betas[t, u +", "reg = fastemit_lambda * (alphas[T - 1, U - 1]", "+ 1, U - 1] + log_probs[t, U - 1,", "torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths,", "alignment[t, u] = emit # reg = fastemit_lambda * (alignment[T", "= alphas[t, U - 1] + betas[t, U - 1]", "fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen,", "labels: Labels of shape [B, U] blank: Index of the", "np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U - 1]", "and the log likelihood of this backward step. \"\"\" T,", "labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch( acts.detach().cpu().numpy(),", "for b in range(log_probs.shape[0]): t = int(flen[b]) u = int(glen[b])", "step. \"\"\" T, U, _ = log_probs.shape betas = np.zeros((T,", "fastemit_lambda > 0.0: for u, l in enumerate(labels): grads[:, u,", "computation of FastEmit regularization from the paper - [FastEmit: Low-latency", "ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape)", "glen: Length vector of the target sequence. blank: Id of", "labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads =", "variable. betas: Unused. Tensor of shape [T, U] which represents", "{T}, Expected max T from input lengths: {max_T}\") if U", "alignment = np.zeros((T, U), dtype='float32') # # for t in", ":u, :] = g reg = fastemit_regularization( log_probs[b, :t, :u,", "{lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0]", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts, labels, act_lens, label_lens)", "[T, U] which represents the backward variable. blank: Index of", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "in enumerate(labels): grads[:, u, l] = alphas[:, u] + betas[:,", "for u in range(1, U): alphas[0, u] = alphas[0, u", "Args: log_probs: Tensor of shape [T, U, V+1] labels: Unused.", "1, 0] + log_probs[t - 1, 0, blank] for u", "1, U - 1] + betas[T - 1, U -", "matrix (TxU) 2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "Computes probability of the forward variable alpha. Args: log_probs: Tensor", "1] + log_probs[T - 1, u, labels[u]] for t in", "certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32,", "# # Copyright 2018-2019, <NAME> # # Licensed under the", "U - 1] + betas[T - 1, U - 1])", "\"gradients only computed for log_probs - please \" \"mark other", "= emit # reg = fastemit_lambda * (alignment[T - 1,", "U - 1] + log_probs[T - 1, U - 1,", "act_lens, label_lens): assert len(labels.size()) == 2 _assert_no_grad(labels) _assert_no_grad(act_lens) _assert_no_grad(label_lens) certify_inputs(acts,", "rights reserved. # # Licensed under the Apache License, Version", "in range(1, T): for u in range(1, U): no_emit =", "u] = emit # reg = fastemit_lambda * (alignment[T -", "backward variable. blank: Index of the blank token. fastemit_lambda: Float", "size] labels: 1D array with shape [output time steps] blank:", "input lengths: {max_T}\") if U != max_U + 1: raise", "blank] for u in reversed(range(U - 1)): betas[T - 1,", "\" f\"Log probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] !=", "of the batch. Args: log_probs: [B, T, U, V+1]. Activation", "- 1], alphas, betas, blank, fastemit_lambda ) ll += reg", "shape [B, U] blank: Index of the blank token. Returns:", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "log_probs[t - 1, 0, blank] for u in range(1, U):", "alphas[0, u - 1] + log_probs[0, u - 1, labels[u", "= torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2, 1,", "betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\"", "alphas[t - 1, 0] + log_probs[t - 1, 0, blank]", "token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: The", "Float scaling factor for FastEmit regularization. Returns: Batch of transducer", "specific language governing permissions and # limitations under the License.", "# # for t in range(0, T): # alignment[t, U", "blank] for u in range(1, U): alphas[0, u] = alphas[0,", "in the beginning. flen: Length vector of the acoustic sequence.", "(loss) and the gradients of the activation matrix. \"\"\" grads", "U] alphas: Tensor of shape [T, U] which represents the", "fastemit regularization alignments T, U, _ = log_probs.shape # alignment", "label index of blank token fastemit_lambda: Float scaling factor for", "= torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3] if", "u] = np.logaddexp(emit, no_emit) loglike = alphas[T - 1, U", "truth labels with <SOS> padded as blank token in the", "target sequence. blank: Id of the blank token. fastemit_lambda: Float", "labels[b, : u - 1], alphas, betas, blank, fastemit_lambda )", "1: raise ValueError(f\"Output length mismatch! Given U: {U}, Expected max", "# you may not use this file except in compliance", "of shape [T, U, V+1] labels: Unused. Labels of shape", "for t in range(0, T): # alignment[t, U - 1]", "compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients", "import torch from torch.autograd import Function, Variable from torch.nn import", "scaling factor for FastEmit regularization. Returns: float: The negative log-likelihood", "u - 1, labels[u - 1]] for t in range(1,", "check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0]", "need of computing the betas alignment matrix reg = fastemit_lambda", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "above is equivalent to below, without need of computing above", "- 1)): no_emit = betas[t + 1, u] + log_probs[t,", "- 1, :, blank] = alphas[: T - 1, :]", "= np.zeros((T, U), dtype='f') betas[T - 1, U - 1]", "regularization. Returns: The regularized negative log likelihood - lambda *", "+ 1, u] + log_probs[t, u, blank] emit = betas[t,", "under the Apache License, Version 2.0 (the \"License\"); # you", "array: Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs, labels,", "= fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens,", "V+1] with respect to the forward log probability \"\"\" T,", "len + 1, vocab size] labels: 1D array with shape", "the License. # # Copyright 2018-2019, <NAME> # # Licensed", "alignment matrix reg = fastemit_lambda * (alphas[T - 1, U", "log_probs: Tensor of shape [T, U, V+1] labels: Labels of", "u|x) \"\"\" # General calculation of the fastemit regularization alignments", "assert not tensor.requires_grad, ( \"gradients only computed for log_probs -", "the forward log probability \"\"\" T, U, _ = log_probs.shape", "T, U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like", "T): for u in range(1, U): no_emit = alphas[t -", "from torch.nn import Module def check_type(var, t, name): if var.dtype", "- 1, u] = betas[T - 1, u + 1]", "beta. Args: log_probs: Tensor of shape [T, U, V+1] labels:", "- 1]) # The above is also equivalent to below,", ") costs = torch.FloatTensor([sum(costs)]) grads = torch.Tensor(grads).to(acts) ctx.grads = grads", "f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\"", "Given U: {U}, Expected max U from target lengths: {max_U}", "0, blank] for u in range(1, U): alphas[0, u] =", "blank, fastemit_lambda) grads[b, :t, :u, :] = g reg =", "def transduce(log_probs, labels, blank=0, fastemit_lambda=0.0): \"\"\" Args: log_probs: 3D array", "betas, blank, fastemit_lambda): \"\"\" Describes the computation of FastEmit regularization", "- 1, :] + betas[1:, :] # // grad to", "0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt", "1, U - 1] = log_probs[T - 1, U -", "the computation of FastEmit regularization from the paper - [FastEmit:", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "flen: Length vector of the acoustic sequence. glen: Length vector", "= alphas[t - 1, u] + log_probs[t - 1, u,", "only computed for log_probs - please \" \"mark other tensors", "transducer forward log probabilities (loss) and the gradients of the", "of computing above # reg = fastemit_lambda * (alphas[T -", "log_probs: Tensor of shape [T, U, V+1] labels: Unused. Labels", "the forward variable probabilities - alpha of shape [T, U]", "check_type(var, t, name): if var.dtype is not t: raise TypeError(\"{}", "betas[t, u + 1] # alignment[t, u] = emit #", "gradients of the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs", "regularization. Returns: float: The negative log-likelihood 3D array: Gradients with", "the log_probs with respect to the log probability of this", "def backward(ctx, grad_output): return ctx.grads, None, None, None, None, None", "with respect to the log probability of this step occuring.", "Index of the blank token. fastemit_lambda: Float scaling factor for", "the betas alignment matrix reg = fastemit_lambda * (alphas[T -", "per example. \" f\"Given label lengths dim : {label_lengths.shape[0]}, \"", ":t, :u, :] = g reg = fastemit_regularization( log_probs[b, :t,", "output len + 1, vocab size] labels: 1D array with", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "the log likelihood of this forward step. \"\"\" T, U,", "0] + log_probs[t - 1, 0, blank] for u in", "= betas[t, u + 1] + log_probs[t, u, labels[u]] betas[t,", "return costs, grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels,", "class RNNTLoss(Module): \"\"\" Parameters: `blank_label` (int): default 0 - label", "CORPORATION. All rights reserved. # # Licensed under the Apache", "shape [T, U] which represents the forward variable. betas: Unused.", "variable beta. Args: log_probs: Tensor of shape [T, U, V+1]", "= np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]): t", "lengths dim: {lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" )", "betas[0, 0] # == alphas[T - 1, U - 1]", "Apache License, Version 2.0 (the \"License\"); # you may not", "0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank = blank", "either express or implied. # See the License for the", "1]] for t in range(1, T): for u in range(1,", "the beginning. flen: Length vector of the acoustic sequence. glen:", "flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of", "- 1]] for t in range(1, T): for u in", "certify_inputs(acts, labels, act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts,", "without need of computing the betas alignment matrix reg =", "alphas[t, u] + log_probs[t, u, labels[u]] + betas[t, u +", "below, without need of computing the betas alignment matrix reg", "the backward variable probabilities - beta of shape [T, U]", "# for t in range(0, T): # for u in", "label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01)", "blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer loss of the batch.", "self.rnnt(acts, labels, act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__':", "+ betas[t, u + 1] # alignment[t, u] = emit", "dtype='float32') # # for t in range(0, T): # alignment[t,", "U, V+1] labels: Unused. Labels of shape [B, U] alphas:", "Index of the blank token. Returns: Gradients of shape [T,", "def __init__(self, blank: int = 0, fastemit_lambda: float = 0.0):", "U - 1, blank] = alphas[T - 1, U -", "U, V+1]. Activation matrix normalized with log-softmax. labels: [B, U+1]", "Copyright 2018-2019, <NAME> # # Licensed under the Apache License,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "the License. import numpy as np import torch from torch.autograd", "- 1, labels[u - 1]] for t in range(1, T):", "def forward(self, acts, labels, act_lens, label_lens): assert len(labels.size()) == 2", "betas[t, U - 1] = betas[t + 1, U -", "log_probs[T - 1, U - 1, blank] return alphas, loglike", "log_probs[T - 1, u, labels[u]] for t in reversed(range(T -", "def _assert_no_grad(tensor): assert not tensor.requires_grad, ( \"gradients only computed for", "forward log probabilities (loss) and the gradients of the activation", "\" f\"Given label lengths dim : {label_lengths.shape[0]}, \" f\"Log probs", "Unused. Labels of shape [B, U] alphas: Tensor of shape", "of transducer forward log probabilities (loss) and the gradients of", "the backward variable. labels: Labels of shape [B, U] blank:", "need of computing above # reg = fastemit_lambda * (alphas[T", "= betas[t + 1, u] + log_probs[t, u, blank] emit", "u] + log_probs[t, u, labels[u]] + betas[t, u + 1]", "log_probs[0, u - 1, labels[u - 1]] for t in", ":t, :u, :], labels[b, : u - 1], blank, fastemit_lambda)", "respect to the unnormalized input actications 2d arrays: Alphas matrix", "blank] emit = alphas[t, u - 1] + log_probs[t, u", "torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\")", "in reversed(range(U - 1)): betas[T - 1, u] = betas[T", "# reg = fastemit_lambda * (alignment[T - 1, U -", "betas[T - 1, U - 1]) # The above is", "T): # for u in range(0, U - 1): #", "betas = transduce(log_probs[b, :t, :u, :], labels[b, : u -", "lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths,", "np.logaddexp(emit, no_emit) return betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas,", "raise ValueError(\"{} must be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths,", "for FastEmit regularization. Returns: Batch of transducer forward log probabilities", "fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u - 1],", "int(glen[b]) + 1 ll, g, alphas, betas = transduce(log_probs[b, :t,", "and the log likelihood of this forward step. \"\"\" T,", "= [] for b in range(log_probs.shape[0]): t = int(flen[b]) u", "grads = -np.exp(grads + log_probs - log_like) if fastemit_lambda >", "# alignment[t, u] = emit # reg = fastemit_lambda *", "input actications 2d arrays: Alphas matrix (TxU) 2d array: Betas", "dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\")", "- 1, U - 1] + log_probs[T - 1, U", "= (1.0 + fastemit_lambda) * grads[:, u, l] return grads", "t, name): if var.dtype is not t: raise TypeError(\"{} must", "1, :, blank] = alphas[: T - 1, :] +", "gradients of the log_probs with respect to the log probability", "labels[u - 1]] for t in range(1, T): for u", "check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have", "int = 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank", "fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\" def __init__(self,", "log_probs.shape[0]: raise ValueError( f\"Must have a length per example. \"", "use this file except in compliance with the License. #", "blank, fastemit_lambda) return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels,", "blank self.fastemit_lambda = fastemit_lambda self.rnnt = _RNNT.apply def forward(self, acts,", "reserved. # # Licensed under the Apache License, Version 2.0", "labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0, 0]", "of blank token fastemit_lambda: Float scaling factor for FastEmit regularization.", "* (alphas[T - 1, U - 1] + betas[T -", "1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])],", "- 1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T", "probability of this step occuring. Args: Args: log_probs: Tensor of", "costs = [] for b in range(log_probs.shape[0]): t = int(flen[b])", "probabilities (loss) and the gradients of the activation matrix. \"\"\"", "token in the beginning. flen: Length vector of the acoustic", "tensors as not requiring gradients\" ) def forward_pass(log_probs, labels, blank):", "max_T: raise ValueError(f\"Input length mismatch! Given T: {T}, Expected max", "is also equivalent to below, without need of computing the", "if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0) acts =", "= fastemit_regularization( log_probs[b, :t, :u, :], labels[b, : u -", "# limitations under the License. # # Copyright 2018-2019, <NAME>", "u, labels[u]] betas[t, u] = np.logaddexp(emit, no_emit) return betas, betas[0,", "V+1] alphas: Tensor of shape [T, U] which represents the", "label_lengths.shape[0] != log_probs.shape[0]: raise ValueError( \"Must have a label length", "Labels of shape [B, U] alphas: Tensor of shape [T,", "- 1] + log_probs[t, u - 1, labels[u - 1]]", "likelihood of this forward step. \"\"\" T, U, _ =", "1, \"label_lenghts\") max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U", "in compliance with the License. # You may obtain a", "T != max_T: raise ValueError(f\"Input length mismatch! Given T: {T},", "reg = fastemit_lambda * (alignment[T - 1, U - 1])", "software # distributed under the License is distributed on an", "FastEmit regularization from the paper - [FastEmit: Low-latency Streaming ASR", "shape [T, U, V+1] alphas: Tensor of shape [T, U]", "1] # // grad to last blank transition grads[T -", "* grads[:, u, l] return grads def fastemit_regularization(log_probs, labels, alphas,", "ValueError(f\"Input length mismatch! Given T: {T}, Expected max T from", "1, U - 1]) # The above is equivalent to", "-float(\"inf\")) log_like = betas[0, 0] # == alphas[T - 1,", "probability of the forward variable alpha. Args: log_probs: Tensor of", "backward variable probabilities - beta of shape [T, U] and", "t = int(flen[b]) u = int(glen[b]) + 1 ll, g,", "the blank token. fastemit_lambda: Float scaling factor for FastEmit regularization.", "check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\")", "V+1] labels: Unused. Labels of shape [B, U] alphas: Tensor", "acts = torch.randn(1, 2, 5, 3) labels = torch.tensor([[0, 2,", "shape [T, U, V+1] labels: Labels of shape [B, U]", "1, U - 1, blank] for t in reversed(range(T -", "\"\"\" T, U, _ = log_probs.shape alphas = np.zeros((T, U),", "with shape [input len, output len + 1, vocab size]", "None, None, None, None, None class RNNTLoss(Module): \"\"\" Parameters: `blank_label`", "Labels of shape [B, U] blank: Index of the blank", "and # limitations under the License. import numpy as np", "of shape [T, U] which represents the backward variable. labels:", "act_lens, label_lens, self.blank, self.fastemit_lambda) if __name__ == '__main__': loss =", "u + 1] grads = -np.exp(grads + log_probs - log_like)", "The regularized negative log likelihood - lambda * P˜(At, u|x)", "u, blank] emit = betas[t, u + 1] + log_probs[t,", "return ctx.grads, None, None, None, None, None class RNNTLoss(Module): \"\"\"", "1)): no_emit = betas[t + 1, u] + log_probs[t, u,", "u = int(glen[b]) + 1 ll, g, alphas, betas =", "1] grads = -np.exp(grads + log_probs - log_like) if fastemit_lambda", "with the License. # You may obtain a copy of", "alphas[t - 1, u] + log_probs[t - 1, u, blank]", "contiguous\".format(name)) def check_dim(var, dim, name): if len(var.shape) != dim: raise", "grad to label transition for u, l in enumerate(labels): grads[:,", "0] = alphas[t - 1, 0] + log_probs[t - 1,", "log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] #", "act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val =", "1, blank] for t in reversed(range(T - 1)): betas[t, U", "not var.is_contiguous(): raise ValueError(\"{} must be contiguous\".format(name)) def check_dim(var, dim,", "check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\") check_type(label_lengths, torch.int32, \"label_lengths\") check_type(lengths,", "as np import torch from torch.autograd import Function, Variable from", "log_probs[t, u - 1, labels[u - 1]] alphas[t, u] =", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "betas: Unused. Tensor of shape [T, U] which represents the", "= torch.max(label_lengths) T, U = log_probs.shape[1:3] if T != max_T:", "the activation matrix. \"\"\" grads = np.zeros_like(log_probs) costs = []", "beginning. flen: Length vector of the acoustic sequence. glen: Length", "= betas[t + 1, U - 1] + log_probs[t, U", "- 1)): betas[T - 1, u] = betas[T - 1,", "be {}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs,", "Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T, U, V+1] labels:", "+ log_probs[t - 1, u, blank] emit = alphas[t, u", "of the blank token. fastemit_lambda: Float scaling factor for FastEmit", "len, output len + 1, vocab size] labels: 1D array", "check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError(", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "of shape [T, U, V+1] alphas: Tensor of shape [T,", "len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name, dim)) def", "[] for b in range(log_probs.shape[0]): t = int(flen[b]) u =", "(alignment[T - 1, U - 1]) # The above is", "transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the transducer", "[input len, output len + 1, vocab size] labels: 1D", "limitations under the License. # # Copyright 2018-2019, <NAME> #", "backward(ctx, grad_output): return ctx.grads, None, None, None, None, None class", "blank): \"\"\" Computes probability of the backward variable beta. Args:", "CONDITIONS OF ANY KIND, either express or implied. # See", "enumerate(labels): grads[:, u, l] = alphas[:, u] + betas[:, u", "range(1, U): no_emit = alphas[t - 1, u] + log_probs[t", "forward variable alpha. Args: log_probs: Tensor of shape [T, U,", "grads = np.zeros_like(log_probs) costs = [] for b in range(log_probs.shape[0]):", "of the backward variable beta. Args: log_probs: Tensor of shape", "np.zeros((T, U), dtype='f') for t in range(1, T): alphas[t, 0]", "token. Returns: A tuple of the forward variable probabilities -", "which represents the forward variable. betas: Tensor of shape [T,", "equivalent to below, without need of computing the betas alignment", "costs, grads = transduce_batch( acts.detach().cpu().numpy(), labels.cpu().numpy(), act_lens.cpu().numpy(), label_lens.cpu().numpy(), blank, fastemit_lambda,", "alignment[t, U - 1] = alphas[t, U - 1] +", "\" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log probs dim :", "check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T", "range(1, U): alphas[0, u] = alphas[0, u - 1] +", "Args: log_probs: Tensor of shape [T, U, V+1] alphas: Tensor", ") ll += reg costs.append(ll) return costs, grads class _RNNT(Function):", "for FastEmit regularization. \"\"\" def __init__(self, blank: int = 0,", "U - 1): # emit = alphas[t, u] + log_probs[t,", "0] # == alphas[T - 1, U - 1] +", "length per example. \" f\"Given lengths dim: {lengths.shape[0]}, \" f\"Log", "= forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank)", ":], labels[b, : u - 1], alphas, betas, blank, fastemit_lambda", "no_emit) loglike = alphas[T - 1, U - 1] +", "u + 1] + log_probs[T - 1, u, labels[u]] for", "log probability of this step occuring. Args: Args: log_probs: Tensor", "log probability \"\"\" T, U, _ = log_probs.shape grads =", "alphas[0, u] = alphas[0, u - 1] + log_probs[0, u", "U - 1] # // grad to last blank transition", "= torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def backward(ctx,", "unnormalized input actications 2d arrays: Alphas matrix (TxU) 2d array:", "fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: Batch of", "\"\"\" Computes probability of the forward variable alpha. Args: log_probs:", "\"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if", "fastemit_lambda: Float scaling factor for FastEmit regularization. Returns: float: The", "* (alignment[T - 1, U - 1]) # The above", "return grads def fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\"", "in range(1, T): alphas[t, 0] = alphas[t - 1, 0]", "of shape [B, U] blank: Index of the blank token.", "with <SOS> padded as blank token in the beginning. flen:", "= 0, fastemit_lambda: float = 0.0): super(RNNTLoss, self).__init__() self.blank =", "matrix reg = fastemit_lambda * (alphas[T - 1, U -", "grads class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens,", "Parameters: `blank_label` (int): default 0 - label index of blank", "self.rnnt = _RNNT.apply def forward(self, acts, labels, act_lens, label_lens): assert", "blank token. fastemit_lambda: Float scaling factor for FastEmit regularization. Returns:", "dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts, labels, act_lens,", "matrix. \"\"\" grads = np.zeros_like(log_probs) costs = [] for b", "Compute the transducer loss of the batch. Args: log_probs: [B,", "Float scaling factor for FastEmit regularization. Returns: The regularized negative", "- log_like) if fastemit_lambda > 0.0: for u, l in", "\"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise", "U - 1] grads[: T - 1, :, blank] =", "betas def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute", "1]] alphas[t, u] = np.logaddexp(emit, no_emit) loglike = alphas[T -", "negative log likelihood - lambda * P˜(At, u|x) \"\"\" #", "+ log_probs[t - 1, 0, blank] for u in range(1,", "max T from input lengths: {max_T}\") if U != max_U", "u, blank] emit = alphas[t, u - 1] + log_probs[t,", "shape [T, U] and the log likelihood of this backward", "which represents the forward variable. betas: Unused. Tensor of shape", "float: The negative log-likelihood 3D array: Gradients with respect to", "is not t: raise TypeError(\"{} must be {}\".format(name, t)) def", "1, u + 1] + log_probs[T - 1, u, labels[u]]", "1] + log_probs[0, u - 1, labels[u - 1]] for", "2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32)", "betas, labels, blank, fastemit_lambda): \"\"\" Computes the gradients of the", "f\"Log probs dim : {log_probs.shape[0]}\" ) check_dim(log_probs, 4, \"log_probs\") check_dim(labels,", "acts, labels, act_lens, label_lens, blank, fastemit_lambda): costs, grads = transduce_batch(", "<SOS> padded as blank token in the beginning. flen: Length", "labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels, torch.int32, \"labels\")", "computing above # reg = fastemit_lambda * (alphas[T - 1,", "= 0.0): super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda", "shape [T, U, V+1] labels: Unused. Labels of shape [B,", "U] blank: Index of the blank token. Returns: Gradients of", "with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape [T,", "Computes the gradients of the log_probs with respect to the", "length per example. \" f\"Given label lengths dim : {label_lengths.shape[0]},", "\"\"\" Describes the computation of FastEmit regularization from the paper", "log likelihood - lambda * P˜(At, u|x) \"\"\" # General", "U - 1] = log_probs[T - 1, U - 1,", "dim : {label_lengths.shape[0]}, \" f\"Log probs dim : {log_probs.shape[0]}\" )", "alphas: Tensor of shape [T, U] which represents the forward", "grads[:, u, l] = (1.0 + fastemit_lambda) * grads[:, u,", "= backward_pass(log_probs, labels, blank) grads = compute_gradient(log_probs, alphas, betas, labels,", "max_T = torch.max(lengths) max_U = torch.max(label_lengths) T, U = log_probs.shape[1:3]", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "regularization. Returns: Batch of transducer forward log probabilities (loss) and", "u] + betas[:, u + 1] grads = -np.exp(grads +", "fastemit_lambda) grads[b, :t, :u, :] = g reg = fastemit_regularization(", "check_type(lengths, torch.int32, \"lengths\") check_contiguous(log_probs, \"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths,", "of shape [T, U, V+1] labels: Labels of shape [B,", "regularization from the paper - [FastEmit: Low-latency Streaming ASR with", "{max_T}\") if U != max_U + 1: raise ValueError(f\"Output length", "return -ll_forward, grads, alphas, betas def transduce_batch(log_probs, labels, flen, glen,", "1] + betas[T - 1, U - 1] # //", "= log_probs.shape alphas = np.zeros((T, U), dtype='f') for t in", "lengths: {max_T}\") if U != max_U + 1: raise ValueError(f\"Output", "// grad to last blank transition grads[T - 1, U", "grads = torch.Tensor(grads).to(acts) ctx.grads = grads return costs @staticmethod def", "Describes the computation of FastEmit regularization from the paper -", ":u, :], labels[b, : u - 1], alphas, betas, blank,", "if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a length", "log_probs[t - 1, u, blank] emit = alphas[t, u -", "`blank_label` (int): default 0 - label index of blank token", "of the fastemit regularization alignments T, U, _ = log_probs.shape", "labels[u]] + betas[t, u + 1] # alignment[t, u] =", "\"log_probs\") check_contiguous(labels, \"labels\") check_contiguous(label_lengths, \"label_lengths\") check_contiguous(lengths, \"lengths\") if lengths.shape[0] !=", "respect to the forward log probability \"\"\" T, U, _", "normalized with log-softmax. labels: [B, U+1] - ground truth labels", "1): # emit = alphas[t, u] + log_probs[t, u, labels[u]]", "lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a length per", "{}D\".format(name, dim)) def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32,", "alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads, alphas, betas", "Version 2.0 (the \"License\"); # you may not use this", "fastemit_regularization(log_probs, labels, alphas, betas, blank, fastemit_lambda): \"\"\" Describes the computation", "of shape [T, U] and the log likelihood of this", "u, l in enumerate(labels): grads[:, u, l] = alphas[:, u]", "Float scaling factor for FastEmit regularization. Returns: float: The negative", "TypeError(\"{} must be {}\".format(name, t)) def check_contiguous(var, name): if not", "l in enumerate(labels): grads[:, u, l] = alphas[:, u] +", "steps] blank: Index of the blank token. fastemit_lambda: Float scaling", "labels = torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2],", "Tensor of shape [T, U] which represents the forward variable.", "with log-softmax. labels: [B, U+1] - ground truth labels with", "by applicable law or agreed to in writing, software #", "of shape [T, U] which represents the forward variable. betas:", "# # for t in range(0, T): # for u", "// grad to label transition for u, l in enumerate(labels):", "np.full(log_probs.shape, -float(\"inf\")) log_like = betas[0, 0] # == alphas[T -", "step. \"\"\" T, U, _ = log_probs.shape alphas = np.zeros((T,", "check_dim(log_probs, 4, \"log_probs\") check_dim(labels, 2, \"labels\") check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths,", "u, l] = (1.0 + fastemit_lambda) * grads[:, u, l]", "+ 1 ll, g, alphas, betas = transduce(log_probs[b, :t, :u,", "labels: Unused. Labels of shape [B, U] alphas: Tensor of", "of computing the betas alignment matrix reg = fastemit_lambda *", "likelihood of this backward step. \"\"\" T, U, _ =", "!= log_probs.shape[0]: raise ValueError( f\"Must have a length per example.", "represents the forward variable. betas: Unused. Tensor of shape [T,", "blank transition grads[T - 1, U - 1, blank] =", "forward_pass(log_probs, labels, blank) betas, ll_backward = backward_pass(log_probs, labels, blank) grads", "grads = compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward,", "log_probs.shape[0]: raise ValueError( \"Must have a label length per example.", "u, labels[u]] for t in reversed(range(T - 1)): for u", "grad to last blank transition grads[T - 1, U -", "Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of", "sequence. blank: Id of the blank token. fastemit_lambda: Float scaling", "t)) def check_contiguous(var, name): if not var.is_contiguous(): raise ValueError(\"{} must", "def transduce_batch(log_probs, labels, flen, glen, blank=0, fastemit_lambda=0.0): \"\"\" Compute the", "u] = alphas[0, u - 1] + log_probs[0, u -", "shape [output time steps] blank: Index of the blank token.", "regularization. \"\"\" def __init__(self, blank: int = 0, fastemit_lambda: float", "[B, U] blank: Index of the blank token. Returns: A", "blank token in the beginning. flen: Length vector of the", "torch.tensor([[0, 2, 1, 2]], dtype=torch.int32) act_lens = torch.tensor([2], dtype=torch.int32) label_lens", "dtype='f') betas[T - 1, U - 1] = log_probs[T -", "1, U - 1] + log_probs[t, U - 1, blank]", "alphas[:, u] + betas[:, u + 1] grads = -np.exp(grads", "def certify_inputs(log_probs, labels, lengths, label_lengths): # check_type(log_probs, torch.float32, \"log_probs\") check_type(labels,", "\"\"\" # General calculation of the fastemit regularization alignments T,", "applicable law or agreed to in writing, software # distributed", "blank): \"\"\" Computes probability of the forward variable alpha. Args:", "Alphas matrix (TxU) 2d array: Betas matrix (TxU) \"\"\" alphas,", "betas, betas[0, 0] def compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda):", "(alphas[T - 1, U - 1] + betas[T - 1,", "= compute_gradient(log_probs, alphas, betas, labels, blank, fastemit_lambda) return -ll_forward, grads,", "reversed(range(T - 1)): for u in reversed(range(U - 1)): no_emit", "blank token. Returns: A tuple of the backward variable probabilities", "The negative log-likelihood 3D array: Gradients with respect to the", "Batch of transducer forward log probabilities (loss) and the gradients", "forward log probability \"\"\" T, U, _ = log_probs.shape grads", "the backward variable beta. Args: log_probs: Tensor of shape [T,", "+ fastemit_lambda) * grads[:, u, l] return grads def fastemit_regularization(log_probs,", "blank token fastemit_lambda: Float scaling factor for FastEmit regularization. \"\"\"", "for u, l in enumerate(labels): grads[:, u, l] = (1.0", "and the gradients of the activation matrix. \"\"\" grads =", "check_dim(lengths, 1, \"lenghts\") check_dim(label_lengths, 1, \"label_lenghts\") max_T = torch.max(lengths) max_U", "shape [T, U] which represents the forward variable. betas: Tensor", "# You may obtain a copy of the License at", "betas[t + 1, U - 1] + log_probs[t, U -", "torch from torch.autograd import Function, Variable from torch.nn import Module", "blank: Id of the blank token. fastemit_lambda: Float scaling factor", "U, _ = log_probs.shape grads = np.full(log_probs.shape, -float(\"inf\")) log_like =", "emit = alphas[t, u - 1] + log_probs[t, u -", "= alphas[T - 1, U - 1] grads[: T -", "U), dtype='f') for t in range(1, T): alphas[t, 0] =", "ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs: Tensor of shape", "if fastemit_lambda > 0.0: for u, l in enumerate(labels): grads[:,", "time steps] blank: Index of the blank token. fastemit_lambda: Float", "probs dim : {log_probs.shape[0]}\" ) if label_lengths.shape[0] != log_probs.shape[0]: raise", "The above is equivalent to below, without need of computing", "betas[1:, :] # // grad to label transition for u,", "not requiring gradients\" ) def forward_pass(log_probs, labels, blank): \"\"\" Computes", "2d array: Betas matrix (TxU) \"\"\" alphas, ll_forward = forward_pass(log_probs,", "if len(var.shape) != dim: raise ValueError(\"{} must be {}D\".format(name, dim))", "self.blank, self.fastemit_lambda) if __name__ == '__main__': loss = RNNTLoss(fastemit_lambda=0.01) torch.manual_seed(0)", "blank] return alphas, loglike def backward_pass(log_probs, labels, blank): \"\"\" Computes", "1] + log_probs[T - 1, U - 1, blank] return", "likelihood - lambda * P˜(At, u|x) \"\"\" # General calculation", "V+1] labels: Labels of shape [B, U] blank: Index of", "variable. labels: Labels of shape [B, U] blank: Index of", "U != max_U + 1: raise ValueError(f\"Output length mismatch! Given", "[FastEmit: Low-latency Streaming ASR with Sequence-level Emission Regularization](https://arxiv.org/abs/2010.11148) Args: log_probs:", "- 1, U - 1, blank]) return -reg def transduce(log_probs,", "+ betas[T - 1, U - 1] # // grad", "U - 1] = betas[t + 1, U - 1]", "in enumerate(labels): grads[:, u, l] = (1.0 + fastemit_lambda) *", "torch.tensor([2], dtype=torch.int32) label_lens = torch.tensor([len(labels[0])], dtype=torch.int32) loss_val = loss(acts, labels,", "\" \"mark other tensors as not requiring gradients\" ) def", "target lengths: {max_U} + 1\") def _assert_no_grad(tensor): assert not tensor.requires_grad,", "1, u] = betas[T - 1, u + 1] +", "torch.nn import Module def check_type(var, t, name): if var.dtype is", "(int): default 0 - label index of blank token fastemit_lambda:", "from the paper - [FastEmit: Low-latency Streaming ASR with Sequence-level", "\"License\"); # you may not use this file except in", "have a label length per example. \" f\"Given label lengths", "labels: [B, U+1] - ground truth labels with <SOS> padded", "super(RNNTLoss, self).__init__() self.blank = blank self.fastemit_lambda = fastemit_lambda self.rnnt =", "# // grad to last blank transition grads[T - 1,", "3D array: Gradients with respect to the unnormalized input actications", "= alphas[t - 1, 0] + log_probs[t - 1, 0,", "act_lens, label_lens) acts = torch.nn.functional.log_softmax(acts, -1) return self.rnnt(acts, labels, act_lens,", "\"lengths\") if lengths.shape[0] != log_probs.shape[0]: raise ValueError( f\"Must have a", "U+1] - ground truth labels with <SOS> padded as blank", "u - 1, labels[u - 1]] alphas[t, u] = np.logaddexp(emit,", "def forward_pass(log_probs, labels, blank): \"\"\" Computes probability of the forward" ]
[ "self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000,", "class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples =", "numpy as np import math from dataset_specifications.dataset import Dataset class", "model with 2 components def sample_ys(self, xs): n = xs.shape[0]", "__init__(self): super().__init__() self.name = \"swirls\" self.n_samples = { \"train\": 2000,", "import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self):", "\"val\": 1000, \"test\": 1000, } self.y_dim = 2 # 2D", "samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys", "np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0]", "xs): n = xs.shape[0] components = np.random.randint(2, size=n) # uniform", "\"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\": 1000,", "math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles),", "np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form 2d", "form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys =", "sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n) #", "super().__init__() self.name = \"swirls\" self.n_samples = { \"train\": 2000, \"val\":", "heteroskedastic Gaussian mixture model with 2 components def sample_ys(self, xs):", "Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise =", "\"test\": 1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian", "def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys =", "= 2 # 2D heteroskedastic Gaussian mixture model with 2", "np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def", "mixture model with 2 components def sample_ys(self, xs): n =", "to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n,", "sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs)", "self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\": 1000, }", "# 2D heteroskedastic Gaussian mixture model with 2 components def", "= 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return", "axis=1) noise = np.random.randn(n, 2) # samples form 2d gaussian", "(math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1)", "def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2, size=n)", "2d gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means", "means + std*noise return ys def sample(self, n): xs =", "SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples = {", "= means + std*noise return ys def sample(self, n): xs", "1000, \"test\": 1000, } self.y_dim = 2 # 2D heteroskedastic", "{ \"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim =", "import numpy as np import math from dataset_specifications.dataset import Dataset", "= np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples", "xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles =", "components def sample_ys(self, xs): n = xs.shape[0] components = np.random.randint(2,", "components = np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components", "import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\"", "2 components def sample_ys(self, xs): n = xs.shape[0] components =", "0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise return ys", "with 2 components def sample_ys(self, xs): n = xs.shape[0] components", "ys = means + std*noise return ys def sample(self, n):", "1000, } self.y_dim = 2 # 2D heteroskedastic Gaussian mixture", "= np.random.randint(2, size=n) # uniform 0,1 angles = math.pi*components +", "+ (math.pi/2.)*xs[:,0] # Angles to centers means = np.stack((np.cos(angles), np.sin(angles)),", "2 # 2D heteroskedastic Gaussian mixture model with 2 components", "n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return", "self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model with", "Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples", "2000, \"val\": 1000, \"test\": 1000, } self.y_dim = 2 #", "= \"swirls\" self.n_samples = { \"train\": 2000, \"val\": 1000, \"test\":", "as np import math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset):", "xs = np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return np.concatenate((xs,", "= xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1 angles", "Gaussian mixture model with 2 components def sample_ys(self, xs): n", "= { \"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim", "# uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles", "gaussian std = 0.3 - 0.2*np.abs(xs-1.) ys = means +", "2D heteroskedastic Gaussian mixture model with 2 components def sample_ys(self,", "<reponame>joeloskarsson/CGAN-regression import numpy as np import math from dataset_specifications.dataset import", "+ std*noise return ys def sample(self, n): xs = np.random.uniform(low=0.,", "std*noise return ys def sample(self, n): xs = np.random.uniform(low=0., high=2.,", "# samples form 2d gaussian std = 0.3 - 0.2*np.abs(xs-1.)", "angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means", "size=n) # uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] #", "0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers", "= np.random.randn(n, 2) # samples form 2d gaussian std =", "np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return np.concatenate((xs, ys), axis=1)", "= np.random.uniform(low=0., high=2., size=(n,1)) ys = self.sample_ys(xs) return np.concatenate((xs, ys),", "math from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__()", "centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2)", "2) # samples form 2d gaussian std = 0.3 -", "from dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name", "= math.pi*components + (math.pi/2.)*xs[:,0] # Angles to centers means =", "std = 0.3 - 0.2*np.abs(xs-1.) ys = means + std*noise", "dataset_specifications.dataset import Dataset class SwirlsSet(Dataset): def __init__(self): super().__init__() self.name =", "# Angles to centers means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise", "np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) # samples form", "- 0.2*np.abs(xs-1.) ys = means + std*noise return ys def", "noise = np.random.randn(n, 2) # samples form 2d gaussian std", "uniform 0,1 angles = math.pi*components + (math.pi/2.)*xs[:,0] # Angles to", "0.2*np.abs(xs-1.) ys = means + std*noise return ys def sample(self,", "return ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1))", "def __init__(self): super().__init__() self.name = \"swirls\" self.n_samples = { \"train\":", "np.random.randn(n, 2) # samples form 2d gaussian std = 0.3", "n = xs.shape[0] components = np.random.randint(2, size=n) # uniform 0,1", "means = np.stack((np.cos(angles), np.sin(angles)), axis=1) noise = np.random.randn(n, 2) #", "} self.y_dim = 2 # 2D heteroskedastic Gaussian mixture model", "ys def sample(self, n): xs = np.random.uniform(low=0., high=2., size=(n,1)) ys", "\"train\": 2000, \"val\": 1000, \"test\": 1000, } self.y_dim = 2" ]
[ "import summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None:", "#!/usr/bin/env python import time from package.oss.cov_json import get_json_report from package.oss.init", "# collect coverage data from json profiles if options.need_summary: summarize_jsons(", "python import time from package.oss.cov_json import get_json_report from package.oss.init import", "cpp tests get_json_report(test_list, options) # collect coverage data from json", "package.util.setting import TestPlatform def report_coverage() -> None: start_time = time.time()", "time from package.oss.cov_json import get_json_report from package.oss.init import initialization from", "from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def report_coverage()", "get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from", "time.time() (options, test_list, interested_folders) = initialization() # run cpp tests", "interested_folders) = initialization() # run cpp tests get_json_report(test_list, options) #", "package.oss.cov_json import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import", "None: start_time = time.time() (options, test_list, interested_folders) = initialization() #", "package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import", "run cpp tests get_json_report(test_list, options) # collect coverage data from", "coverage data from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders,", "data from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"],", "# run cpp tests get_json_report(test_list, options) # collect coverage data", "def report_coverage() -> None: start_time = time.time() (options, test_list, interested_folders)", "start_time = time.time() (options, test_list, interested_folders) = initialization() # run", "<gh_stars>10-100 #!/usr/bin/env python import time from package.oss.cov_json import get_json_report from", "(options, test_list, interested_folders) = initialization() # run cpp tests get_json_report(test_list,", "get_json_report(test_list, options) # collect coverage data from json profiles if", "collect coverage data from json profiles if options.need_summary: summarize_jsons( test_list,", "from package.util.setting import TestPlatform def report_coverage() -> None: start_time =", "profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time )", "import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform", "import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons", "package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def report_coverage() ->", "if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if", "summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__ ==", "from package.oss.init import initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting", "TestPlatform def report_coverage() -> None: start_time = time.time() (options, test_list,", "test_list, interested_folders) = initialization() # run cpp tests get_json_report(test_list, options)", "= initialization() # run cpp tests get_json_report(test_list, options) # collect", "test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__ == \"__main__\":", "options) # collect coverage data from json profiles if options.need_summary:", "import TestPlatform def report_coverage() -> None: start_time = time.time() (options,", "options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__", "from package.oss.cov_json import get_json_report from package.oss.init import initialization from package.tool.summarize_jsons", "report_coverage() -> None: start_time = time.time() (options, test_list, interested_folders) =", "= time.time() (options, test_list, interested_folders) = initialization() # run cpp", "from json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS,", "initialization() # run cpp tests get_json_report(test_list, options) # collect coverage", "tests get_json_report(test_list, options) # collect coverage data from json profiles", "json profiles if options.need_summary: summarize_jsons( test_list, interested_folders, [\"\"], TestPlatform.OSS, start_time", "initialization from package.tool.summarize_jsons import summarize_jsons from package.util.setting import TestPlatform def", "interested_folders, [\"\"], TestPlatform.OSS, start_time ) if __name__ == \"__main__\": report_coverage()", "import time from package.oss.cov_json import get_json_report from package.oss.init import initialization", "summarize_jsons from package.util.setting import TestPlatform def report_coverage() -> None: start_time", "-> None: start_time = time.time() (options, test_list, interested_folders) = initialization()" ]
[ "np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet", "LogisticRegression().fit(vects, labels) # We've done the model fitting, now to", "user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet", "a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns", "User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\"", "given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1", "'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st user", "User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect =", "for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels =", "= np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for", "return which user is more likely to say a given", "vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which", "= np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done", "to 1st user passed in, or 0 for second. \"\"\"", "= np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect])", "import numpy as np from sklearn.linear_model import LogisticRegression from .models", "from .models import User from .twitter import vectorize_tweet def predict_user(user1_name,", "Determine and return which user is more likely to say", "We've done the model fitting, now to predict... hypo_tweet_vect =", "= User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet in", "log_reg = LogisticRegression().fit(vects, labels) # We've done the model fitting,", "= User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect", "user is more likely to say a given Tweet. Example:", "np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done the model", "in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))])", "predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which user is", "def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return which user", "# We've done the model fitting, now to predict... hypo_tweet_vect", "tweet_text): \"\"\" Determine and return which user is more likely", "user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name == user2_name).one()", "'Lambda School Rocks!') Returns 1 corresponding to 1st user passed", "import LogisticRegression from .models import User from .twitter import vectorize_tweet", "1 corresponding to 1st user passed in, or 0 for", "Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to", "== user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect", "user2_name, tweet_text): \"\"\" Determine and return which user is more", "from sklearn.linear_model import LogisticRegression from .models import User from .twitter", "Rocks!') Returns 1 corresponding to 1st user passed in, or", "np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels", "for tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in", "which user is more likely to say a given Tweet.", "0 for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2", "or 0 for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one()", "user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects =", "np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've done the", "model fitting, now to predict... hypo_tweet_vect = vectorize_tweet(tweet_text) return log_reg.predict(np.array(hypo_tweet_vect).reshape(1,-1))", ".twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and", "user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect = np.array([tweet.vect", "more likely to say a given Tweet. Example: predict_user('ausen', 'elonmusk',", "tweet in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets])", "User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets])", "for second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 =", "say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!')", "numpy as np from sklearn.linear_model import LogisticRegression from .models import", "user2_name).one() user1_vect = np.array([tweet.vect for tweet in user1.tweets]) user2_vect =", "labels) # We've done the model fitting, now to predict...", "from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine", "user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) #", "user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg", "1st user passed in, or 0 for second. \"\"\" user1", "user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects = np.vstack([user1_vect,", "in user1.tweets]) user2_vect = np.array([tweet.vect for tweet in user2.tweets]) vects", "user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect for", "the model fitting, now to predict... hypo_tweet_vect = vectorize_tweet(tweet_text) return", "second. \"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name", "= LogisticRegression().fit(vects, labels) # We've done the model fitting, now", "== user1_name).one() user2 = User.query.filter(User.name == user2_name).one() user1_vect = np.array([tweet.vect", "user passed in, or 0 for second. \"\"\" user1 =", "likely to say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda", "\"\"\" user1 = User.query.filter(User.name == user1_name).one() user2 = User.query.filter(User.name ==", "np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels)", "sklearn.linear_model import LogisticRegression from .models import User from .twitter import", "= np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects,", "is more likely to say a given Tweet. Example: predict_user('ausen',", "np from sklearn.linear_model import LogisticRegression from .models import User from", "import User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text):", "labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg = LogisticRegression().fit(vects, labels) # We've", "in, or 0 for second. \"\"\" user1 = User.query.filter(User.name ==", "passed in, or 0 for second. \"\"\" user1 = User.query.filter(User.name", "vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)), np.zeros(len(user2.tweets))]) log_reg =", "School Rocks!') Returns 1 corresponding to 1st user passed in,", "done the model fitting, now to predict... hypo_tweet_vect = vectorize_tweet(tweet_text)", "LogisticRegression from .models import User from .twitter import vectorize_tweet def", "corresponding to 1st user passed in, or 0 for second.", "Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding", "\"\"\" Determine and return which user is more likely to", "to say a given Tweet. Example: predict_user('ausen', 'elonmusk', 'Lambda School", "predict_user('ausen', 'elonmusk', 'Lambda School Rocks!') Returns 1 corresponding to 1st", "and return which user is more likely to say a", "import vectorize_tweet def predict_user(user1_name, user2_name, tweet_text): \"\"\" Determine and return", "Returns 1 corresponding to 1st user passed in, or 0", "tweet in user2.tweets]) vects = np.vstack([user1_vect, user2_vect]) labels = np.concatenate([np.ones(len(user1.tweets)),", "as np from sklearn.linear_model import LogisticRegression from .models import User", ".models import User from .twitter import vectorize_tweet def predict_user(user1_name, user2_name," ]
[ "work worldwide through the CC0 1.0 # Universal public domain", "1.0 # Universal public domain dedication. __version__ = '1.0.0' #", "waives # copyright and related rights in the work worldwide", "through the CC0 1.0 # Universal public domain dedication. __version__", "part of groupthink. # https://github.com/emanuelfeld/groupthink # This project is in", "-*- coding: utf-8 -*- # This file is part of", "groupthink. # https://github.com/emanuelfeld/groupthink # This project is in the public", "the United States. # Additionally, the Government of the District", "coding: utf-8 -*- # This file is part of groupthink.", "worldwide through the CC0 1.0 # Universal public domain dedication.", "the District of Columbia waives # copyright and related rights", "# Additionally, the Government of the District of Columbia waives", "# -*- coding: utf-8 -*- # This file is part", "District of Columbia waives # copyright and related rights in", "and related rights in the work worldwide through the CC0", "CC0 1.0 # Universal public domain dedication. __version__ = '1.0.0'", "domain within the United States. # Additionally, the Government of", "# copyright and related rights in the work worldwide through", "# Universal public domain dedication. __version__ = '1.0.0' # NOQA", "the public domain within the United States. # Additionally, the", "#!/usr/bin/env python # -*- coding: utf-8 -*- # This file", "# This file is part of groupthink. # https://github.com/emanuelfeld/groupthink #", "of the District of Columbia waives # copyright and related", "-*- # This file is part of groupthink. # https://github.com/emanuelfeld/groupthink", "within the United States. # Additionally, the Government of the", "States. # Additionally, the Government of the District of Columbia", "copyright and related rights in the work worldwide through the", "in the work worldwide through the CC0 1.0 # Universal", "Government of the District of Columbia waives # copyright and", "the work worldwide through the CC0 1.0 # Universal public", "of groupthink. # https://github.com/emanuelfeld/groupthink # This project is in the", "https://github.com/emanuelfeld/groupthink # This project is in the public domain within", "# This project is in the public domain within the", "United States. # Additionally, the Government of the District of", "project is in the public domain within the United States.", "This project is in the public domain within the United", "is in the public domain within the United States. #", "utf-8 -*- # This file is part of groupthink. #", "the CC0 1.0 # Universal public domain dedication. __version__ =", "file is part of groupthink. # https://github.com/emanuelfeld/groupthink # This project", "rights in the work worldwide through the CC0 1.0 #", "the Government of the District of Columbia waives # copyright", "This file is part of groupthink. # https://github.com/emanuelfeld/groupthink # This", "public domain within the United States. # Additionally, the Government", "of Columbia waives # copyright and related rights in the", "Columbia waives # copyright and related rights in the work", "# https://github.com/emanuelfeld/groupthink # This project is in the public domain", "python # -*- coding: utf-8 -*- # This file is", "related rights in the work worldwide through the CC0 1.0", "Additionally, the Government of the District of Columbia waives #", "in the public domain within the United States. # Additionally,", "is part of groupthink. # https://github.com/emanuelfeld/groupthink # This project is" ]
[ "at the begining or end of sequence random_move: If true,", "sequence debug: If true, only use the first 100 samples", "json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in))", "sample_name) with open(sample_path, 'r') as f: video_info = json.load(f) #", "If true, perform randomly but continuously changed transformation to input", "= data_numpy[:, :, :, 0:self.num_person_out] # match poses between 2", "18 #joint self.M = self.num_person_out #person def __len__(self): return len(self.sample_name)", "shape of data should be (N, C, T, V, M)", "number of people the feeder can observe in the input", "= debug self.data_path = data_path self.label_path = label_path self.random_choose =", "sort by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for", "# sys import os import sys import numpy as np", "has skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s for", "__len__(self): return len(self.sample_name) def __iter__(self): return self def __getitem__(self, index):", "data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0", "nn from torchvision import datasets, transforms # operation from .", "0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0] =", "data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) #", "true, randomly choose a portion of the input sequence random_shift:", "sample_id]) # ignore the samples which does not has skeleton", "= 3 #channel self.T = 90000 #frame self.V = 18", "# output data shape (N, C, T, V, M) self.N", "s in zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton]", "true, perform randomly but continuously changed transformation to input sequence", "= os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label", "return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k):", ":, m] = pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2]", "# torch import torch import torch.nn as nn from torchvision", "C, T, V, M) label_path: the path to label random_choose:", "transforms # operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\"", "number of people the feeder in the output sequence debug:", "> 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy =", "get & check label index label = video_info['label_index'] assert (self.label[index]", "randomly choose a portion of the input sequence random_shift: If", "M) # get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path,", "np import random import pickle import json # torch import", "samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False,", ":, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out]", "2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match", "V, M) self.N = len(self.sample_name) #sample self.C = 3 #channel", "self.sample_name = [ s for h, s in zip(has_skeleton, self.sample_name)", "1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >=", ". import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action", "__iter__(self): return self def __getitem__(self, index): # output shape (C,", "= video_info['label_index'] assert (self.label[index] == label) # data augmentation if", "self.M = self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self):", "input sequence num_person_out: The number of people the feeder in", "= skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index)", "pose between two frames num_person_in: The number of people the", "self.debug = debug self.data_path = data_path self.label_path = label_path self.random_choose", "enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score,", "enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1,", "data_numpy[1][data_numpy[2] == 0] = 0 # get & check label", ">= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert", "which does not has skeleton sequence if self.ignore_empty_sample: self.sample_name =", "1 # print(\" \",count, \" \") # centralization data_numpy[0:2] =", "label index label = video_info['label_index'] assert (self.label[index] == label) #", "between two frames num_person_in: The number of people the feeder", "data_numpy, label def top_k(self, score, top_k): assert (all(self.label >= 0))", "self.random_move = random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out", "return data_numpy, label def top_k(self, score, top_k): assert (all(self.label >=", "self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data()", "[l in rank[i, -top_k:] for i, l in enumerate(self.label)] return", "assert (all(self.label >= 0)) rank = score.argsort() hit_top_k = [l", "load file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name =", "as f: video_info = json.load(f) # fill data_numpy data_numpy =", "# match poses between 2 frames if self.pose_matching: data_numpy =", "to label random_choose: If true, randomly choose a portion of", "data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match poses between", "'r') as f: video_info = json.load(f) # fill data_numpy data_numpy", "m] = pose[1::2] data_numpy[2, frame_index, :, m] = score #", "import os import sys import numpy as np import random", "return len(self.sample_name) def __iter__(self): return self def __getitem__(self, index): #", "torchvision import datasets, transforms # operation from . import tools", "__init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5,", "def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False,", "sample_id = [name.split('.')[0] for name in self.sample_name] self.label = np.array(", "# ignore the samples which does not has skeleton sequence", "# get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name)", "samples which does not has skeleton sequence if self.ignore_empty_sample: self.sample_name", "people the feeder in the output sequence debug: If true,", "#channel self.T = 90000 #frame self.V = 18 #joint self.M", "== 0] = 0 data_numpy[1][data_numpy[2] == 0] = 0 #", "len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return", "/ len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label >= 0))", "label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False):", "self.sample_name = self.sample_name[0:2] # load label label_path = self.label_path with", "self.V = 18 #joint self.M = self.num_person_out #person def __len__(self):", "torch import torch import torch.nn as nn from torchvision import", "data_numpy[2, frame_index, :, m] = score # count += 1", "label label_path = self.label_path with open(label_path) as f: label_info =", "in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id])", "sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r')", "data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :, m]", "= json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name] self.label", "as nn from torchvision import datasets, transforms # operation from", "in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self,", "(all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score):", "l in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k) def", "use the first 100 samples \"\"\" def __init__(self, data_path, label_path,", "data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] ==", "# centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0]", "end of sequence random_move: If true, perform randomly but continuously", "the feeder in the output sequence debug: If true, only", "h ] self.label = self.label[has_skeleton] # output data shape (N,", "= num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample =", "tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >= 0))", "* 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert (all(self.label", "assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self,", "debug: If true, only use the first 100 samples \"\"\"", "0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy)", "If true, randomly pad zeros at the begining or end", "output data shape (N, C, T, V, M) self.N =", "in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose = skeleton_info['pose']", "debug=False): self.debug = debug self.data_path = data_path self.label_path = label_path", "\" \") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2]", "of the output sequence pose_matching: If ture, match the pose", "# get & check label index label = video_info['label_index'] assert", ":, :, 0:self.num_person_out] # match poses between 2 frames if", "window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path =", "[label_info[id]['has_skeleton'] for id in sample_id]) # ignore the samples which", "in rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k)", "sequence window_size: The length of the output sequence pose_matching: If", "\"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1,", "random_shift: If true, randomly pad zeros at the begining or", ":].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t, :, :]", "self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if", "-top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0", "by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t,", "random_move: If true, perform randomly but continuously changed transformation to", "in sample_id]) # ignore the samples which does not has", "frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def", "data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0] = 0", "tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k): assert (all(self.label", "= random_shift self.random_move = random_move self.window_size = window_size self.num_person_in =", "top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score,", "\"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton dataset Arguments:", "if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0:", "sys import numpy as np import random import pickle import", "= tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k): assert", "class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton", "(-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:,", "T, V, M) label_path: the path to label random_choose: If", "frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] =", "#person def __len__(self): return len(self.sample_name) def __iter__(self): return self def", "tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size >", "+= 1 # print(\" \",count, \" \") # centralization data_numpy[0:2]", "label = video_info['label_index'] assert (self.label[index] == label) # data augmentation", "to '.npy' data, the shape of data should be (N,", "of people the feeder in the output sequence debug: If", "100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False,", "open(label_path) as f: label_info = json.load(f) sample_id = [name.split('.')[0] for", "num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path = data_path self.label_path", "as f: label_info = json.load(f) sample_id = [name.split('.')[0] for name", "centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] =", "data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0", "but continuously changed transformation to input sequence window_size: The length", "score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >= 0)) return", "assert (self.label[index] == label) # data augmentation if self.random_shift: data_numpy", "randomly pad zeros at the begining or end of sequence", "tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2, :, :,", "# count += 1 # print(\" \",count, \" \") #", "sys import os import sys import numpy as np import", "0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] # match poses", "t, s in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:,", "sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info", "self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): #", "of sequence random_move: If true, perform randomly but continuously changed", "top_k) def calculate_recall_precision(self, score): assert (all(self.label >= 0)) return tools.calculate_recall_precision(self.label,", "a portion of the input sequence random_shift: If true, randomly", "= random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out =", "label_info = json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name]", "self.V, self.num_person_in)) count = 0 for frame_info in video_info['data']: frame_index", "= label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move =", "0] = 0 # get & check label index label", "check label index label = video_info['label_index'] assert (self.label[index] == label)", "from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based", "self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score,", ":, m] = pose[1::2] data_numpy[2, frame_index, :, m] = score", "(N, C, T, V, M) self.N = len(self.sample_name) #sample self.C", "pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :,", "t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :,", "(self.label[index] == label) # data augmentation if self.random_shift: data_numpy =", "self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score sort_index =", "file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2]", "'.npy' data, the shape of data should be (N, C,", "= ignore_empty_sample self.load_data() def load_data(self): # load file list self.sample_name", "id in sample_id]) # ignore the samples which does not", "of data should be (N, C, T, V, M) label_path:", "data_path: the path to '.npy' data, the shape of data", "def calculate_recall_precision(self, score): assert (all(self.label >= 0)) return tools.calculate_recall_precision(self.label, score)", "in the output sequence debug: If true, only use the", "__getitem__(self, index): # output shape (C, T, V, M) #", "[ s for h, s in zip(has_skeleton, self.sample_name) if h", "m] = pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2,", "id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in", "zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton] # output", "self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index =", "random import pickle import json # torch import torch import", "Arguments: data_path: the path to '.npy' data, the shape of", "self.T, self.V, self.num_person_in)) count = 0 for frame_info in video_info['data']:", "if h ] self.label = self.label[has_skeleton] # output data shape", "the pose between two frames num_person_in: The number of people", "for t, s in enumerate(sort_index): data_numpy[:, t, :, :] =", "= self.label_path with open(label_path) as f: label_info = json.load(f) sample_id", "tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in", "video_info['label_index'] assert (self.label[index] == label) # data augmentation if self.random_shift:", "self.label_path = label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move", "output sequence debug: If true, only use the first 100", "window_size: The length of the output sequence pose_matching: If ture,", "self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton", "= score.argsort() hit_top_k = [l in rank[i, -top_k:] for i,", "label) # data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if", "the output sequence debug: If true, only use the first", "= os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info =", "input sequence window_size: The length of the output sequence pose_matching:", "datasets, transforms # operation from . import tools class Feeder_UCF(torch.utils.data.Dataset):", "0] = 0 data_numpy[1][data_numpy[2] == 0] = 0 # get", "sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id]) #", "random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug =", "frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m", "m] = score # count += 1 # print(\" \",count,", "import random import pickle import json # torch import torch", "If ture, match the pose between two frames num_person_in: The", ">= 0)) rank = score.argsort() hit_top_k = [l in rank[i,", "import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition", "label def top_k(self, score, top_k): assert (all(self.label >= 0)) rank", "0)) return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label", "the path to label random_choose: If true, randomly choose a", "self.label_path with open(label_path) as f: label_info = json.load(f) sample_id =", "= num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def", "# fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count", "self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample", "h, s in zip(has_skeleton, self.sample_name) if h ] self.label =", "(C, T, V, M) # get data sample_name = self.sample_name[index]", "dataset Arguments: data_path: the path to '.npy' data, the shape", "index label = video_info['label_index'] assert (self.label[index] == label) # data", "pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path = data_path", "operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for", "= [l in rank[i, -top_k:] for i, l in enumerate(self.label)]", "observe in the input sequence num_person_out: The number of people", "from torchvision import datasets, transforms # operation from . import", "length of the output sequence pose_matching: If ture, match the", "name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in", "torch.nn as nn from torchvision import datasets, transforms # operation", "self.random_choose = random_choose self.random_shift = random_shift self.random_move = random_move self.window_size", "= np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array(", "ture, match the pose between two frames num_person_in: The number", ":, 0:self.num_person_out] # match poses between 2 frames if self.pose_matching:", "data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif", "len(self.sample_name) #sample self.C = 3 #channel self.T = 90000 #frame", "M) label_path: the path to label random_choose: If true, randomly", "pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load file", "data_numpy[:, t, :, :] = data_numpy[:, t, :, s].transpose((1, 2,", "self def __getitem__(self, index): # output shape (C, T, V,", "to input sequence window_size: The length of the output sequence", "skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m]", ":, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t, :,", "be (N, C, T, V, M) label_path: the path to", "the input sequence random_shift: If true, randomly pad zeros at", "if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy,", "shape (N, C, T, V, M) self.N = len(self.sample_name) #sample", "V, M) label_path: the path to label random_choose: If true,", "os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f: video_info = json.load(f)", "= self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as", "m >= self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score']", "label random_choose: If true, randomly choose a portion of the", "import torch import torch.nn as nn from torchvision import datasets,", "skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0,", "load_data(self): # load file list self.sample_name = os.listdir(self.data_path) if self.debug:", "score # count += 1 # print(\" \",count, \" \")", "in zip(has_skeleton, self.sample_name) if h ] self.label = self.label[has_skeleton] #", "= random_choose self.random_shift = random_shift self.random_move = random_move self.window_size =", "tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size)", "sequence num_person_out: The number of people the feeder in the", "label_path: the path to label random_choose: If true, randomly choose", "s for h, s in zip(has_skeleton, self.sample_name) if h ]", "frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :, m] =", "C, T, V, M) self.N = len(self.sample_name) #sample self.C =", "os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path", "== 0] = 0 # get & check label index", "self.label[has_skeleton] # output data shape (N, C, T, V, M)", "fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count =", "of people the feeder can observe in the input sequence", "sequence pose_matching: If ture, match the pose between two frames", "Feeder for skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path:", "in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]):", "= np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore the", "self.random_shift = random_shift self.random_move = random_move self.window_size = window_size self.num_person_in", "frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in", "The number of people the feeder can observe in the", "= tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2, :,", "= frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >=", "frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in:", "= tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy,", "feeder in the output sequence debug: If true, only use", "ignore_empty_sample self.load_data() def load_data(self): # load file list self.sample_name =", "sequence random_move: If true, perform randomly but continuously changed transformation", "action recognition in kinetics-skeleton dataset Arguments: data_path: the path to", "in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t, :,", "with open(label_path) as f: label_info = json.load(f) sample_id = [name.split('.')[0]", "skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose =", "path to label random_choose: If true, randomly choose a portion", "# load file list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name", "continuously changed transformation to input sequence window_size: The length of", "the input sequence num_person_out: The number of people the feeder", "= len(self.sample_name) #sample self.C = 3 #channel self.T = 90000", "= data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2]", "# print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index,", "augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy =", "debug self.data_path = data_path self.label_path = label_path self.random_choose = random_choose", "#sample self.C = 3 #channel self.T = 90000 #frame self.V", "data_numpy = np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for", "self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy", "M) self.N = len(self.sample_name) #sample self.C = 3 #channel self.T", "score.argsort() hit_top_k = [l in rank[i, -top_k:] for i, l", "self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self): return self", "randomly but continuously changed transformation to input sequence window_size: The", "if self.ignore_empty_sample: self.sample_name = [ s for h, s in", "data_path self.label_path = label_path self.random_choose = random_choose self.random_shift = random_shift", "num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample", "self.sample_name[0:2] # load label label_path = self.label_path with open(label_path) as", "= [name.split('.')[0] for name in self.sample_name] self.label = np.array( [label_info[id]['label_index']", "pose_matching: If ture, match the pose between two frames num_person_in:", "only use the first 100 samples \"\"\" def __init__(self, data_path,", "score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s", "in the input sequence num_person_out: The number of people the", "f: label_info = json.load(f) sample_id = [name.split('.')[0] for name in", "= tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size", "for skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path: the", "kinetics-skeleton dataset Arguments: data_path: the path to '.npy' data, the", "= 0 for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for", "not has skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s", "#joint self.M = self.num_person_out #person def __len__(self): return len(self.sample_name) def", "0 data_numpy[1][data_numpy[2] == 0] = 0 # get & check", "# sort by score sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1)", "data, the shape of data should be (N, C, T,", "elif self.window_size > 0: data_numpy = tools.auto_pading(data_numpy, self.window_size) if self.random_move:", "zeros at the begining or end of sequence random_move: If", "torch import torch.nn as nn from torchvision import datasets, transforms", "print(\" \",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2] -", "pose[1::2] data_numpy[2, frame_index, :, m] = score # count +=", "in kinetics-skeleton dataset Arguments: data_path: the path to '.npy' data,", "import datasets, transforms # operation from . import tools class", "random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug self.data_path", "# operation from . import tools class Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder", "return self def __getitem__(self, index): # output shape (C, T,", "0 for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m,", "index): # output shape (C, T, V, M) # get", "V, M) # get data sample_name = self.sample_name[index] sample_path =", "between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy,", "def top_k(self, score, top_k): assert (all(self.label >= 0)) rank =", "score = skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index,", "sequence if self.ignore_empty_sample: self.sample_name = [ s for h, s", "self.num_person_in)) count = 0 for frame_info in video_info['data']: frame_index =", "frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :, m] =", "self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path, 'r') as f:", "get data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with", "int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1,", "data_path, label_path, ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2,", "does not has skeleton sequence if self.ignore_empty_sample: self.sample_name = [", "& check label index label = video_info['label_index'] assert (self.label[index] ==", "self.N = len(self.sample_name) #sample self.C = 3 #channel self.T =", "\") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5 data_numpy[0][data_numpy[2] ==", "label_path self.random_choose = random_choose self.random_shift = random_shift self.random_move = random_move", "output shape (C, T, V, M) # get data sample_name", "count = 0 for frame_info in video_info['data']: frame_index = frame_info['frame_index']", ":, m] = score # count += 1 # print(\"", "= self.num_person_out #person def __len__(self): return len(self.sample_name) def __iter__(self): return", "num_person_in: The number of people the feeder can observe in", "if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self,", "#frame self.V = 18 #joint self.M = self.num_person_out #person def", "feeder can observe in the input sequence num_person_out: The number", "= data_path self.label_path = label_path self.random_choose = random_choose self.random_shift =", ":, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index): data_numpy[:, t,", "The number of people the feeder in the output sequence", "= tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort", "random_move self.window_size = window_size self.num_person_in = num_person_in self.num_person_out = num_person_out", "self.T = 90000 #frame self.V = 18 #joint self.M =", "= pose[0::2] data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index,", "of the input sequence random_shift: If true, randomly pad zeros", "open(sample_path, 'r') as f: video_info = json.load(f) # fill data_numpy", "shape (C, T, V, M) # get data sample_name =", "can observe in the input sequence num_person_out: The number of", "t, :, :] = data_numpy[:, t, :, s].transpose((1, 2, 0))", "self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load file list", "import torch.nn as nn from torchvision import datasets, transforms #", "self.load_data() def load_data(self): # load file list self.sample_name = os.listdir(self.data_path)", "= json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T, self.V,", "enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose = skeleton_info['pose'] score", "poses between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return", "output sequence pose_matching: If ture, match the pose between two", "= 0 # get & check label index label =", "count += 1 # print(\" \",count, \" \") # centralization", "= (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in enumerate(sort_index):", "two frames num_person_in: The number of people the feeder can", "= pose[1::2] data_numpy[2, frame_index, :, m] = score # count", "self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size)", "window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching = pose_matching", "T, V, M) self.N = len(self.sample_name) #sample self.C = 3", "90000 #frame self.V = 18 #joint self.M = self.num_person_out #person", "def __len__(self): return len(self.sample_name) def __iter__(self): return self def __getitem__(self,", "if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score sort_index", "self.debug: self.sample_name = self.sample_name[0:2] # load label label_path = self.label_path", "[label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for", "pad zeros at the begining or end of sequence random_move:", "for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton'] for id", "video_info = json.load(f) # fill data_numpy data_numpy = np.zeros((self.C, self.T,", "= 0 data_numpy[1][data_numpy[2] == 0] = 0 # get &", "video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if", "# load label label_path = self.label_path with open(label_path) as f:", "= pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self): # load", "the output sequence pose_matching: If ture, match the pose between", "= data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:,", "= int(frame_index) # print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2]", "# output shape (C, T, V, M) # get data", "If true, randomly choose a portion of the input sequence", "def __getitem__(self, index): # output shape (C, T, V, M)", "0 # get & check label index label = video_info['label_index']", "should be (N, C, T, V, M) label_path: the path", "in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id in sample_id])", "for frame_info in video_info['data']: frame_index = frame_info['frame_index'] for m, skeleton_info", "match poses between 2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy)", "portion of the input sequence random_shift: If true, randomly pad", "the begining or end of sequence random_move: If true, perform", "tools.auto_pading(data_numpy, self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by", "ignore_empty_sample=True, random_choose=False, random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug", "rank[i, -top_k:] for i, l in enumerate(self.label)] return sum(hit_top_k) *", "perform randomly but continuously changed transformation to input sequence window_size:", "self.random_choose: data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy", "data_numpy = tools.random_choose(data_numpy, self.window_size) elif self.window_size > 0: data_numpy =", "= 90000 #frame self.V = 18 #joint self.M = self.num_person_out", "skeleton sequence if self.ignore_empty_sample: self.sample_name = [ s for h,", "(N, C, T, V, M) label_path: the path to label", "[name.split('.')[0] for name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for", "list self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] #", "with open(sample_path, 'r') as f: video_info = json.load(f) # fill", "s in enumerate(sort_index): data_numpy[:, t, :, :] = data_numpy[:, t,", "len(self.sample_name) def __iter__(self): return self def __getitem__(self, index): # output", "2 frames if self.pose_matching: data_numpy = tools.openpose_match(data_numpy) return data_numpy, label", "json.load(f) sample_id = [name.split('.')[0] for name in self.sample_name] self.label =", "m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break pose", "top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k) def", "data_numpy[1, frame_index, :, m] = pose[1::2] data_numpy[2, frame_index, :, m]", "true, only use the first 100 samples \"\"\" def __init__(self,", "skeleton-based action recognition in kinetics-skeleton dataset Arguments: data_path: the path", "pickle import json # torch import torch import torch.nn as", "sequence random_shift: If true, randomly pad zeros at the begining", "self.label = np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton =", "numpy as np import random import pickle import json #", "true, randomly pad zeros at the begining or end of", "ignore the samples which does not has skeleton sequence if", "num_person_out=2, debug=False): self.debug = debug self.data_path = data_path self.label_path =", "path to '.npy' data, the shape of data should be", "begining or end of sequence random_move: If true, perform randomly", "(all(self.label >= 0)) rank = score.argsort() hit_top_k = [l in", "load label label_path = self.label_path with open(label_path) as f: label_info", "for i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0 /", "data_numpy = tools.openpose_match(data_numpy) return data_numpy, label def top_k(self, score, top_k):", "np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for frame_info in", "if self.debug: self.sample_name = self.sample_name[0:2] # load label label_path =", "json # torch import torch import torch.nn as nn from", "If true, only use the first 100 samples \"\"\" def", "data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose: data_numpy", "import sys import numpy as np import random import pickle", "return tools.top_k_by_category(self.label, score, top_k) def calculate_recall_precision(self, score): assert (all(self.label >=", "f: video_info = json.load(f) # fill data_numpy data_numpy = np.zeros((self.C,", "match the pose between two frames num_person_in: The number of", "self.sample_name = os.listdir(self.data_path) if self.debug: self.sample_name = self.sample_name[0:2] # load", "import json # torch import torch import torch.nn as nn", "random_shift=False, random_move=False, window_size=-1, pose_matching=False, num_person_in=5, num_person_out=2, debug=False): self.debug = debug", "transformation to input sequence window_size: The length of the output", "data sample_name = self.sample_name[index] sample_path = os.path.join(self.data_path, sample_name) with open(sample_path,", "= [ s for h, s in zip(has_skeleton, self.sample_name) if", "score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label, score, top_k)", "print(frame_index) data_numpy[0, frame_index, :, m] = pose[0::2] data_numpy[1, frame_index, :,", "choose a portion of the input sequence random_shift: If true,", "self.ignore_empty_sample: self.sample_name = [ s for h, s in zip(has_skeleton,", "rank = score.argsort() hit_top_k = [l in rank[i, -top_k:] for", "first 100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True, random_choose=False,", "= np.zeros((self.C, self.T, self.V, self.num_person_in)) count = 0 for frame_info", "== label) # data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy)", "i, l in enumerate(self.label)] return sum(hit_top_k) * 1.0 / len(hit_top_k)", ">= self.num_person_in: break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index", "has_skeleton = np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore", "= self.sample_name[0:2] # load label label_path = self.label_path with open(label_path)", "changed transformation to input sequence window_size: The length of the", "pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index) #", "score, top_k): assert (all(self.label >= 0)) rank = score.argsort() hit_top_k", "data_numpy[:, :, :, 0:self.num_person_out] # match poses between 2 frames", "= 18 #joint self.M = self.num_person_out #person def __len__(self): return", "as np import random import pickle import json # torch", "top_k): assert (all(self.label >= 0)) rank = score.argsort() hit_top_k =", "T, V, M) # get data sample_name = self.sample_name[index] sample_path", "= self.label[has_skeleton] # output data shape (N, C, T, V,", "0:self.num_person_out] # match poses between 2 frames if self.pose_matching: data_numpy", "\",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2] - 0.5", "random_shift self.random_move = random_move self.window_size = window_size self.num_person_in = num_person_in", "] self.label = self.label[has_skeleton] # output data shape (N, C,", "data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :,", "top_k(self, score, top_k): assert (all(self.label >= 0)) rank = score.argsort()", "# print(\" \",count, \" \") # centralization data_numpy[0:2] = data_numpy[0:2]", "self.window_size) if self.random_move: data_numpy = tools.random_move(data_numpy) # sort by score", "the shape of data should be (N, C, T, V,", "self.window_size = window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching", "or end of sequence random_move: If true, perform randomly but", "frames num_person_in: The number of people the feeder can observe", "for h, s in zip(has_skeleton, self.sample_name) if h ] self.label", "data should be (N, C, T, V, M) label_path: the", "= window_size self.num_person_in = num_person_in self.num_person_out = num_person_out self.pose_matching =", "np.array( [label_info[id]['has_skeleton'] for id in sample_id]) # ignore the samples", "self.label = self.label[has_skeleton] # output data shape (N, C, T,", "s].transpose((1, 2, 0)) data_numpy = data_numpy[:, :, :, 0:self.num_person_out] #", "random_choose self.random_shift = random_shift self.random_move = random_move self.window_size = window_size", "hit_top_k = [l in rank[i, -top_k:] for i, l in", "= skeleton_info['score'] frame_index = int(frame_index) # print(frame_index) data_numpy[0, frame_index, :,", "sort_index = (-data_numpy[2, :, :, :].sum(axis=1)).argsort(axis=1) for t, s in", "self.data_path = data_path self.label_path = label_path self.random_choose = random_choose self.random_shift", "self.sample_name) if h ] self.label = self.label[has_skeleton] # output data", "data_numpy = tools.random_move(data_numpy) # sort by score sort_index = (-data_numpy[2,", "for m, skeleton_info in enumerate(frame_info[\"skeleton\"]): if m >= self.num_person_in: break", "def top_k_by_category(self, score, top_k): assert (all(self.label >= 0)) return tools.top_k_by_category(self.label,", "the path to '.npy' data, the shape of data should", "os import sys import numpy as np import random import", "for id in sample_id]) # ignore the samples which does", ":, :] = data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy", "break pose = skeleton_info['pose'] score = skeleton_info['score'] frame_index = int(frame_index)", "the first 100 samples \"\"\" def __init__(self, data_path, label_path, ignore_empty_sample=True,", "sum(hit_top_k) * 1.0 / len(hit_top_k) def top_k_by_category(self, score, top_k): assert", "random_choose: If true, randomly choose a portion of the input", "import pickle import json # torch import torch import torch.nn", "0)) rank = score.argsort() hit_top_k = [l in rank[i, -top_k:]", "data shape (N, C, T, V, M) self.N = len(self.sample_name)", ":] = data_numpy[:, t, :, s].transpose((1, 2, 0)) data_numpy =", "- 0.5 data_numpy[0][data_numpy[2] == 0] = 0 data_numpy[1][data_numpy[2] == 0]", "recognition in kinetics-skeleton dataset Arguments: data_path: the path to '.npy'", "if m >= self.num_person_in: break pose = skeleton_info['pose'] score =", "the samples which does not has skeleton sequence if self.ignore_empty_sample:", "# data augmentation if self.random_shift: data_numpy = tools.random_shift(data_numpy) if self.random_choose:", "num_person_out self.pose_matching = pose_matching self.ignore_empty_sample = ignore_empty_sample self.load_data() def load_data(self):", "input sequence random_shift: If true, randomly pad zeros at the", "label_path = self.label_path with open(label_path) as f: label_info = json.load(f)", "people the feeder can observe in the input sequence num_person_out:", "frame_index, :, m] = score # count += 1 #", "def load_data(self): # load file list self.sample_name = os.listdir(self.data_path) if", "import numpy as np import random import pickle import json", "for name in self.sample_name] self.label = np.array( [label_info[id]['label_index'] for id", "The length of the output sequence pose_matching: If ture, match", "the feeder can observe in the input sequence num_person_out: The", "3 #channel self.T = 90000 #frame self.V = 18 #joint", "def __iter__(self): return self def __getitem__(self, index): # output shape", "= score # count += 1 # print(\" \",count, \"", "Feeder_UCF(torch.utils.data.Dataset): \"\"\" Feeder for skeleton-based action recognition in kinetics-skeleton dataset", "self.C = 3 #channel self.T = 90000 #frame self.V =", "np.array( [label_info[id]['label_index'] for id in sample_id]) has_skeleton = np.array( [label_info[id]['has_skeleton']", "num_person_out: The number of people the feeder in the output" ]
[ "'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit',", "('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'),", "Generated by Django 4.0.2 on 2022-03-02 03:29 from django.conf import", "('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning',", "migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE',", "['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date',", "('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'], },", "django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL),", "('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], },", "options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True,", "# Generated by Django 4.0.2 on 2022-03-02 03:29 from django.conf", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM',", "('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)),", "models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'),", "('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),", "Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'),", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()),", "('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)),", "= [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel(", "verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={", "models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual", "models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse',", "by Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings", "primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')),", "}, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "03:29 from django.conf import settings from django.db import migrations, models", "('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary',", "['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')),", "'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description',", "], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id',", "'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white',", "migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)),", "'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user',", "] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments',", "class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit',", "name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description',", "('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')],", "import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [", "[ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge',", "import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True", "to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'], }, ), ]", "verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'),", "True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations =", "], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[ ('id',", "'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'),", "models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural':", "}, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],", "('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'),", "<gh_stars>1-10 # Generated by Django 4.0.2 on 2022-03-02 03:29 from", "serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info',", "('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ],", "('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel(", "verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'),", "max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "import settings from django.db import migrations, models import django.db.models.deletion class", "models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies =", "django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial =", "('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()),", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success',", "options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True,", "('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER',", "Django 4.0.2 on 2022-03-02 03:29 from django.conf import settings from", "models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'),", "2022-03-02 03:29 from django.conf import settings from django.db import migrations,", "from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'),", "fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE',", "= [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "to='core.badge')), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[", "('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering':", "'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT', 'Sexual Content'), ('OTHER', 'Other')],", "models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering':", "models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'),", "), migrations.CreateModel( name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',", "[ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',", "migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies", "models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'], }, ),", "initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ]", "('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING', 'Bullying'), ('SEXUAL_CONTENT',", "migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)),", "name='Requirments', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description',", "Content'), ('OTHER', 'Other')], max_length=50)), ('description', models.TextField()), ('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special',", "('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'), ('info', 'Blue'), ('link',", "models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='Requirments', fields=[", "= True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations", "'Green'), ('info', 'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger',", "to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses', 'ordering': ['-date'],", "operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False,", "'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)),", "serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'), ('BULLYING',", "'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={", "'Black'), ('white', 'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'],", "dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [", "max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel(", "'0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.BigAutoField(auto_created=True,", "'White')], max_length=50)), ('special', models.BooleanField(default=False)), ], options={ 'ordering': ['name'], }, ),", "('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], },", "serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ],", "name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'),", "('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id',", "models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'],", "'ordering': ['name'], }, ), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True,", "models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering': ['name'], }, ),", "from django.conf import settings from django.db import migrations, models import", "primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color', models.CharField(choices=[('success', 'Green'),", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('color',", "models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge',", "primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type', models.CharField(choices=[('ABUSE', 'Abuse'), ('INAPPROPRIATE', 'Inappropriate'), ('SPAM', 'Spam'),", "), migrations.CreateModel( name='Abuse', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('abuse_type',", "migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('vit', '0001_initial'), ] operations = [ migrations.CreateModel( name='Badge', fields=[", "('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name_plural': 'Abuses',", "'Blue'), ('link', 'Purple'), ('primary', 'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark',", "4.0.2 on 2022-03-02 03:29 from django.conf import settings from django.db", "on 2022-03-02 03:29 from django.conf import settings from django.db import", "settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):", "django.conf import settings from django.db import migrations, models import django.db.models.deletion", "('date', models.DateTimeField(auto_now_add=True)), ('to_vit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vit.vit')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={", "('name', models.CharField(max_length=50)), ('description', models.TextField()), ('badge', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.badge')), ], options={ 'ordering':", "'Turquoise'), ('warning', 'Yellow'), ('danger', 'Red'), ('dark', 'Black'), ('white', 'White')], max_length=50))," ]
[ "time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name, destination,", "self.initial_schema = initial_schema self.svc = None def start(self): env =", "name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub", "\"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0',", "def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\":", "stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query, schema_type=pb2.SchemaType(schema_type=schema_type))) return resp.id", "= initial_schema self.svc = None def start(self): env = {", "subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import", "query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel)", "env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self):", "= os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers,", "{ \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\":", "\"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") }", "None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers,", "initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id", "edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port", "as pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or", "destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub =", "if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env)", "= subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill() def", "self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill()", "self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc = None def", "stop(self): self.svc.kill() def create_schema(self, name, destination, query, body, schema_type): with", "body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp", "= input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc =", "= kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema =", "= postgres_config self.initial_schema = initial_schema self.svc = None def start(self):", "tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry:", "pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query,", "= None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\":", "PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers", "self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config", "self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if", "'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is", "import os import subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2", "return self def stop(self): self.svc.kill() def create_schema(self, name, destination, query,", "= kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config =", "tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import", "'0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None:", "as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig", "kafka_brokers self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config = postgres_config", "__init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr =", "subprocess.Popen([EXE], env=env) time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self,", "postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers =", "os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config:", "from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class", "self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc", "import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc", "grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from", "def create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as", "'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry',", "kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema = initial_schema", "EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr,", "env=env) time.sleep(3) return self def stop(self): self.svc.kill() def create_schema(self, name,", "with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema(", "None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self def", "self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port", "import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres", "self.input_port = input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc", "postgres_config self.initial_schema = initial_schema self.svc = None def start(self): env", "\"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not", "import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE =", "input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id =", "kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id", "time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc as", "start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id,", "import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def", "self.svc.kill() def create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\")", "create_schema(self, name, destination, query, body, schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel:", "edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr", "schema_type): with grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp =", "grpc.insecure_channel(f\"localhost:{self.input_port}\") as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema(", "os import subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2 as", "pb2 import tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE", "SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None):", "\"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema)", "} if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE],", "\"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry',", "self def stop(self): self.svc.kill() def create_schema(self, name, destination, query, body,", "self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\")", "input_port self.postgres_config = postgres_config self.initial_schema = initial_schema self.svc = None", "stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name,", "kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr = edge_registry_addr self.kafka_brokers", "pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry'", "self.kafka_group_id = kafka_group_id self.input_port = input_port self.postgres_config = postgres_config self.initial_schema", "class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101',", "as channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body,", "\"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr,", "= pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination,", "initial_schema self.svc = None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\":", "def stop(self): self.svc.kill() def create_schema(self, name, destination, query, body, schema_type):", "self.svc = None def start(self): env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka',", "= { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port,", "is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return", "**self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc =", "= stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query, schema_type=pb2.SchemaType(schema_type=schema_type))) return", "tests.rpc.proto.schema_registry_pb2_grpc as pb2_grpc from tests.common.postgres import PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE')", "import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2 import tests.rpc.proto.schema_registry_pb2_grpc", "= edge_registry_addr self.kafka_brokers = kafka_brokers self.kafka_group_id = kafka_group_id self.input_port =", "env = { \"SCHEMA_REGISTRY_COMMUNICATION_METHOD\": 'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\":", "\"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\": self.edge_registry_addr, **self.postgres_config.to_dict(\"SCHEMA_REGISTRY\") } if self.initial_schema", "or 'schema-registry' class SchemaRegistry: def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig,", "not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3) return self", "import subprocess import time import grpc import tests.rpc.proto.schema_registry_pb2 as pb2", "self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\": '0', \"SCHEMA_REGISTRY_SERVICES__EDGE_REGISTRY_URL\":", "self.initial_schema is not None: env.update(SCHEMA_REGISTRY_IMPORT_FILE=self.initial_schema) self.svc = subprocess.Popen([EXE], env=env) time.sleep(3)", "PostgresConfig EXE = os.getenv('SCHEMA_REGISTRY_EXE') or 'schema-registry' class SchemaRegistry: def __init__(self,", "'kafka', \"SCHEMA_REGISTRY_KAFKA__BROKERS\": self.kafka_brokers, \"SCHEMA_REGISTRY_KAFKA__GROUP_ID\": self.kafka_group_id, \"SCHEMA_REGISTRY_INPUT_PORT\": self.input_port, \"SCHEMA_REGISTRY_MONITORING__OTEL_SERVICE_NAME\": 'schema-registry', \"SCHEMA_REGISTRY_MONITORING__STATUS_PORT\":", "resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'), name=name, insert_destination=destination, query_address=query, schema_type=pb2.SchemaType(schema_type=schema_type)))", "channel: stub = pb2_grpc.SchemaRegistryStub(channel) resp = stub.AddSchema( pb2.NewSchema( definition=bytes(body, 'utf-8'),", "def __init__(self, edge_registry_addr, kafka_brokers, postgres_config: PostgresConfig, kafka_group_id='schema_registry', input_port='50101', initial_schema=None): self.edge_registry_addr" ]
[ "noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark =", "loaded correctly and should route all the requests to a", "asserts, that the routing policy is active and the requests", "import Version # noqa # pylint: disable=unused-import from testsuite import", "from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"),", "testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")]", "to httpbin. (Using the logic that an empty condition should", "rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {},", "from packaging.version import Version # noqa # pylint: disable=unused-import from", "(Using the logic that an empty condition should act as", "route all requests to httpbin. (Using the logic that an", "@pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used", "private_base_url): \"\"\" Sends a request and asserts, that the routing", "\"\"\" When a routing policy is set with an empty", "backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert", "Version # noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION,", "= api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response) assert", "the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url):", "rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest", "response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response)", "service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used as the", "api is used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\"))", "EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def", "= urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request", "and asserts, that the routing policy is active and the", "assert response.status_code == 200 echoed_request = EchoedRequest.create(response) assert echoed_request.headers[\"Host\"] ==", "used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def", "return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing", "private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\"", "condition should act as a catch all rule) \"\"\" proxy", "}]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request", "# pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [", "act as a catch all rule) \"\"\" proxy = service.proxy.list()", "disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION <", "httpbin. (Using the logic that an empty condition should act", "a correct backend. \"\"\" from urllib.parse import urlparse import pytest", "routing policy is set with an empty condition, it should", "import urlparse import pytest from packaging.version import Version # noqa", "packaging.version import Version # noqa # pylint: disable=unused-import from testsuite", "from testsuite import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import", "the routing policy is active and the requests is routed", "the requests to a correct backend. \"\"\" from urllib.parse import", "is active and the requests is routed to the correct", "all requests to httpbin. (Using the logic that an empty", "Asserts, that echo api is used as the default backend", "import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request", "TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from testsuite.echoed_request import", "is set with an empty condition, it should be loaded", "an empty condition should act as a catch all rule)", "requests to a correct backend. \"\"\" from urllib.parse import urlparse", "api_client().get(\"/get\") assert response.status_code == 200 echoed_request = EchoedRequest.create(response) assert echoed_request.headers[\"Host\"]", "all the requests to a correct backend. \"\"\" from urllib.parse", "test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts, that the", "to the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response", "private_base_url): \"\"\" Set the routing policy to route all requests", "@pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing policy to", "= service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\":", "urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200 echoed_request =", "logic that an empty condition should act as a catch", "[ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def", "all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", {", "pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa #", "\"\"\" Set the routing policy to route all requests to", "urlparse import pytest from packaging.version import Version # noqa #", "correct backend. \"\"\" from urllib.parse import urlparse import pytest from", "< Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo", "routed to the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\"))", "an empty condition, it should be loaded correctly and should", "to a correct backend. \"\"\" from urllib.parse import urlparse import", "request and asserts, that the routing policy is active and", "as a catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0,", "policy is set with an empty condition, it should be", "\"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service", "\"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the", "routing policy to route all requests to httpbin. (Using the", "from urllib.parse import urlparse import pytest from packaging.version import Version", "# noqa # pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark", "empty condition should act as a catch all rule) \"\"\"", "\"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code ==", "# pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa", "route all the requests to a correct backend. \"\"\" from", "a routing policy is set with an empty condition, it", "and should route all the requests to a correct backend.", "catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\",", "def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts, that", "set with an empty condition, it should be loaded correctly", "pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url):", "service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and asserts,", "should route all the requests to a correct backend. \"\"\"", "active and the requests is routed to the correct backend", "it should be loaded correctly and should route all the", "pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that", "and the requests is routed to the correct backend (httpbin)", "is routed to the correct backend (httpbin) \"\"\" parsed_url =", "{ \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return", "service(service, private_base_url): \"\"\" Set the routing policy to route all", "\"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url):", "condition, it should be loaded correctly and should route all", "echo api is used as the default backend \"\"\" return", "empty condition, it should be loaded correctly and should route", "rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\":", "parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code == 200", "disable=unused-import from testsuite import TESTED_VERSION, rawobj # noqa # pylint:", "backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set", "requests to httpbin. (Using the logic that an empty condition", "[ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts,", "the correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response =", "Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api", "proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\":", "routing policy is active and the requests is routed to", "pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is", "response.status_code == 200 echoed_request = EchoedRequest.create(response) assert echoed_request.headers[\"Host\"] == parsed_url.hostname", "as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service,", "policy to route all requests to httpbin. (Using the logic", "requests is routed to the correct backend (httpbin) \"\"\" parsed_url", "import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\")", "that the routing policy is active and the requests is", "should act as a catch all rule) \"\"\" proxy =", "\"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends", "backend. \"\"\" from urllib.parse import urlparse import pytest from packaging.version", "should be loaded correctly and should route all the requests", "a request and asserts, that the routing policy is active", "= [ pytest.mark.skipif(\"TESTED_VERSION < Version('2.11')\"), pytest.mark.issue(\"https://issues.redhat.com/browse/THREESCALE-6415\")] @pytest.fixture(scope=\"module\") def service_proxy_settings(private_base_url): \"\"\"", "that an empty condition should act as a catch all", "a catch all rule) \"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig(", "When a routing policy is set with an empty condition,", "rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\" Set the routing policy", "def service(service, private_base_url): \"\"\" Set the routing policy to route", "# noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj", "correctly and should route all the requests to a correct", "testsuite import TESTED_VERSION, rawobj # noqa # pylint: disable=unused-import from", "pylint: disable=unused-import from testsuite.echoed_request import EchoedRequest pytestmark = [ pytest.mark.skipif(\"TESTED_VERSION", "the requests is routed to the correct backend (httpbin) \"\"\"", "Sends a request and asserts, that the routing policy is", "urllib.parse import urlparse import pytest from packaging.version import Version #", "the routing policy to route all requests to httpbin. (Using", "\"\"\" from urllib.parse import urlparse import pytest from packaging.version import", "the logic that an empty condition should act as a", "(httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\") assert response.status_code", "{}, }]})) return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a", "to route all requests to httpbin. (Using the logic that", "Set the routing policy to route all requests to httpbin.", "be loaded correctly and should route all the requests to", "\"\"\" Sends a request and asserts, that the routing policy", "correct backend (httpbin) \"\"\" parsed_url = urlparse(private_base_url(\"httpbin\")) response = api_client().get(\"/get\")", "\"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]}))", "{ \"url\": private_base_url(\"httpbin\"), \"condition\": {}, }]})) return service def test_routing_policy_without_header(api_client,", "proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ {", "default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\") def service(service, private_base_url): \"\"\"", "noqa # pylint: disable=unused-import from testsuite import TESTED_VERSION, rawobj #", "\"\"\" proxy = service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [", "\"\"\" Asserts, that echo api is used as the default", "with an empty condition, it should be loaded correctly and", "service.proxy.list() proxy.policies.insert(0, rawobj.PolicyConfig( \"routing\", { \"rules\": [ { \"url\": private_base_url(\"httpbin\"),", "return service def test_routing_policy_without_header(api_client, private_base_url): \"\"\" Sends a request and", "import pytest from packaging.version import Version # noqa # pylint:", "pytest from packaging.version import Version # noqa # pylint: disable=unused-import", "is used as the default backend \"\"\" return rawobj.Proxy(private_base_url(\"echo_api\")) @pytest.fixture(scope=\"module\")", "policy is active and the requests is routed to the", "that echo api is used as the default backend \"\"\"", "def service_proxy_settings(private_base_url): \"\"\" Asserts, that echo api is used as" ]
[ "It is defining the exchange and topics to be connected", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster'", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "2014 Mirantis Inc. # # Licensed under the Apache License,", "Unless required by applicable law or agreed to in writing,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a", "import oslo.messaging from ceilometer import plugin from ceilometer import sample", "distributed under the License is distributed on an \"AS IS\"", "message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification(", "import plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange',", "for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class", "or # implied. # See the License for the specific", "limitations under the License. from oslo.config import cfg import oslo.messaging", "return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' %", "name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara'", "the specific language governing permissions and # limitations under the", "'%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create' %", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "a sequence of oslo.messaging.Target It is defining the exchange and", "= message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'], user_id=user_id,", "applicable law or agreed to in writing, software # distributed", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE =", "Mirantis Inc. # # Licensed under the Apache License, Version", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "express or # implied. # See the License for the", "def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is defining", "exchange and topics to be connected for this plugin. \"\"\"", "exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name =", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "from ceilometer import plugin from ceilometer import sample OPTS =", "project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA,", "ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name", "you may not use this file except in compliance with", "conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id =", "ANY KIND, either express or # implied. # See the", "= message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster',", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "@staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is", "import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for", "language governing permissions and # limitations under the License. from", "this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics]", "yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'], user_id=user_id, project_id=project_id, message=message)", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "# limitations under the License. from oslo.config import cfg import", "@property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' %", "sequence of oslo.messaging.Target It is defining the exchange and topics", "plugin from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara',", "def event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name,", "event_types(self): return [ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete'", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id']", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "OF ANY KIND, either express or # implied. # See", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def", "topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster')", "# You may obtain a copy of the License at", "[oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message): name", "specific language governing permissions and # limitations under the License.", "plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def", "SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE", "= message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield", "to be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange)", "under the License is distributed on an \"AS IS\" BASIS,", "for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in", "topics to be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self): return", "defining the exchange and topics to be connected for this", "License for the specific language governing permissions and # limitations", "oslo.config import cfg import oslo.messaging from ceilometer import plugin from", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "either express or # implied. # See the License for", "% self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return", "user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'],", "of oslo.messaging.Target It is defining the exchange and topics to", "License. from oslo.config import cfg import oslo.messaging from ceilometer import", "the License for the specific language governing permissions and #", "notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name =", "(the \"License\"); # you may not use this file except", "] @staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It", "Apache License, Version 2.0 (the \"License\"); # you may not", "OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing", "# you may not use this file except in compliance", "get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target It is defining the", "Copyright (c) 2014 Mirantis Inc. # # Licensed under the", "<gh_stars>0 # Copyright (c) 2014 Mirantis Inc. # # Licensed", "= '%s.cluster' % SERVICE @property def event_types(self): return [ '%s.create'", "% self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence of", "the exchange and topics to be connected for this plugin.", "= 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data", "the License is distributed on an \"AS IS\" BASIS, #", "% SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name,", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "is defining the exchange and topics to be connected for", "message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1,", "'%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or #", "'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def", "# # Unless required by applicable law or agreed to", "# implied. # See the License for the specific language", "'%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ]", "[ '%s.create' % self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name,", "'%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod def get_targets(conf):", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "SERVICE @property def event_types(self): return [ '%s.create' % self.resource_name, '%s.update'", "def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id']", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "Version 2.0 (the \"License\"); # you may not use this", "Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase):", "and # limitations under the License. from oslo.config import cfg", "message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id =", "law or agreed to in writing, software # distributed under", "cfg import oslo.messaging from ceilometer import plugin from ceilometer import", "oslo.messaging from ceilometer import plugin from ceilometer import sample OPTS", "# Copyright (c) 2014 Mirantis Inc. # # Licensed under", "in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id", "permissions and # limitations under the License. from oslo.config import", "for topic in conf.notification_topics] def process_notification(self, message): name = message['event_type'].replace(self.resource_name,", "self.resource_name, ] @staticmethod def get_targets(conf): \"\"\"Return a sequence of oslo.messaging.Target", "\"\"\"Return a sequence of oslo.messaging.Target It is defining the exchange", "KIND, either express or # implied. # See the License", "implied. # See the License for the specific language governing", "under the License. from oslo.config import cfg import oslo.messaging from", "cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS)", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"License\"); # you may not use this file except in", "be connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for", "Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name", "default='sahara', help=\"Exchange name for Data Processing notifications.\"), ] cfg.CONF.register_opts(OPTS) SERVICE", "connected for this plugin. \"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self, message):", "[ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"), ]", "the License. from oslo.config import cfg import oslo.messaging from ceilometer", "CONDITIONS OF ANY KIND, either express or # implied. #", "message['_context_user_id'] yield sample.Sample.from_notification( name=name, type=sample.TYPE_DELTA, unit='cluster', volume=1, resource_id=message['payload']['cluster_id'], user_id=user_id, project_id=project_id,", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "= [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange name for Data Processing notifications.\"),", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "See the License for the specific language governing permissions and", "'cluster') project_id = message['payload']['project_id'] user_id = message['_context_user_id'] yield sample.Sample.from_notification( name=name,", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "(c) 2014 Mirantis Inc. # # Licensed under the Apache", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "# See the License for the specific language governing permissions", "governing permissions and # limitations under the License. from oslo.config", "OR CONDITIONS OF ANY KIND, either express or # implied.", "from oslo.config import cfg import oslo.messaging from ceilometer import plugin", "class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' % SERVICE @property def event_types(self):", "You may obtain a copy of the License at #", "% self.resource_name, '%s.update' % self.resource_name, '%s.delete' % self.resource_name, ] @staticmethod", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "\"\"\" return [oslo.messaging.Target(topic=topic, exchange=conf.sahara_control_exchange) for topic in conf.notification_topics] def process_notification(self,", "process_notification(self, message): name = message['event_type'].replace(self.resource_name, 'cluster') project_id = message['payload']['project_id'] user_id", "required by applicable law or agreed to in writing, software", "ceilometer import plugin from ceilometer import sample OPTS = [", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "resource_name = '%s.cluster' % SERVICE @property def event_types(self): return [", "with the License. # You may obtain a copy of", "import cfg import oslo.messaging from ceilometer import plugin from ceilometer", "this file except in compliance with the License. # You", "and topics to be connected for this plugin. \"\"\" return", "oslo.messaging.Target It is defining the exchange and topics to be", "the Apache License, Version 2.0 (the \"License\"); # you may", "cfg.CONF.register_opts(OPTS) SERVICE = 'sahara' class DataProcessing(plugin.NotificationBase): resource_name = '%s.cluster' %", "from ceilometer import sample OPTS = [ cfg.StrOpt('sahara_control_exchange', default='sahara', help=\"Exchange" ]
[ "import pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver):", "') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2)", "self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename) os.remove(self.filename) return file", "= GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type'))", "= pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ')", "selenium.webdriver.support.select import Select from Data.parameters import Data from get_dir import", "colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() +", "self.driver = driver self.filename ='' def test_download_csv(self): self.data = GetData()", "def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data", "reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver = driver", "= Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename =", "time from selenium.webdriver.support.select import Select from Data.parameters import Data from", "Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv'", "test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype", "self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename) os.remove(self.filename)", "self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click()", "os import time from selenium.webdriver.support.select import Select from Data.parameters import", "Data from get_dir import pwd from reuse_func import GetData class", "from get_dir import pwd from reuse_func import GetData class All_records_download():", "self.filename ='' def test_download_csv(self): self.data = GetData() self.p = pwd()", "import GetData class All_records_download(): def __init__(self,driver): self.driver = driver self.filename", "='' def test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click()", "Data.parameters import Data from get_dir import pwd from reuse_func import", "pwd from reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver", "get_dir import pwd from reuse_func import GetData class All_records_download(): def", "colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename", "time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename)", "= self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file = os.path.isfile(self.filename) os.remove(self.filename) return", "All_records_download(): def __init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self):", "self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4)", "self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype =", "from selenium.webdriver.support.select import Select from Data.parameters import Data from get_dir", "from reuse_func import GetData class All_records_download(): def __init__(self,driver): self.driver =", "= driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p", "GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text('", "from Data.parameters import Data from get_dir import pwd from reuse_func", "class All_records_download(): def __init__(self,driver): self.driver = driver self.filename ='' def", "import time from selenium.webdriver.support.select import Select from Data.parameters import Data", "__init__(self,driver): self.driver = driver self.filename ='' def test_download_csv(self): self.data =", "Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir()", "driver self.filename ='' def test_download_csv(self): self.data = GetData() self.p =", "import Data from get_dir import pwd from reuse_func import GetData", "Select from Data.parameters import Data from get_dir import pwd from", "self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file =", "import Select from Data.parameters import Data from get_dir import pwd", "self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall", "self.data.page_loading(self.driver) self.driver.find_element_by_id(Data.Download).click() time.sleep(4) self.filename = self.p.get_download_dir() + '/collectionType_all_data.csv' time.sleep(2) file", "def test_download_csv(self): self.data = GetData() self.p = pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver)", "import os import time from selenium.webdriver.support.select import Select from Data.parameters", "<gh_stars>0 import os import time from selenium.webdriver.support.select import Select from", "GetData class All_records_download(): def __init__(self,driver): self.driver = driver self.filename =''", "pwd() self.driver.find_element_by_xpath(Data.hyper_link).click() self.data.page_loading(self.driver) colltype = Select(self.driver.find_element_by_name('collection_type')) colltype.select_by_visible_text(' Overall ') self.data.page_loading(self.driver)" ]
[ "cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value, path,", "= {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS", "= raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag,", "plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8", "in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE", "MAC check failed. Possibly the key is wrong?', only_once=True) return", "key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM)", "is not None: output_jar.filename = jar.filename return output_jar def _is_path(value):", "except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b''", "names can be determined by snooping on dbus while opening", "not be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies", "name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not", "= p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record", "self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value: {value} !=", "= _get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir'] elif", "class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer =", "0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0:", "desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else:", "DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService", "version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger)", "'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double())", "from firefox without sqlite3 support. ' 'Please use a python", "if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env:", "= Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys',", "at \"{path}\"') with open(path, encoding='utf8') as f: data = json.load(f)", "config = _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome':", "if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name,", "as plaintext Windows: - cookies are either v10 or not", "ImportError: # although sqlite3 is part of the standard library,", "else: raise NotImplementedError(f'Chrome cookie decryption is not supported on this", "because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at", "'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata,", "is_encrypted = not value and encrypted_value if is_encrypted: value =", "try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet'", "occurs in KDE because chrome does not check hasEntry and", "to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet'", "supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will", "if path is None: logger.error('could not find local state file')", "self._v11_key = None if password is None else self.derive_key(password) self._cookie_counts", "- [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def", "# using `dbus-monitor` during startup, it can be observed that", "KDE because chrome does not check hasEntry and instead #", "# it, but that doesn't matter here. return b'' else:", "elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon':", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be", "None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home():", "and store # it, but that doesn't matter here. return", "is None: self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True)", "if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message)", "else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar()", "logger): self._data = data self.cursor = 0 self._logger = logger", "Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise", "logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly", "do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col", "firefox') return jar finally: if cursor is not None: cursor.connection.close()", "DPAPI - not v10: encrypted with DPAPI Sources: - [1]", "logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to", "elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger):", "network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to", "except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as", "col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() ==", "_mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset)", "is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile,", "value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format =", "browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise", "the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False,", "6d} files searched') if file == filename: paths.append(os.path.join(curr_root, file)) return", "support') return YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir()", "Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection #", "not installed. ' 'Please install by running `python3 -m pip", "this sometimes occurs in KDE because chrome does not check", "return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password", "fixed key - v11: AES-CBC encrypted with an OS protected", "classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented by sub", "= Popen( ['security', 'find-generic-password', '-w', # write password to stdout", "if num_bytes < 0: raise ParserError(f'invalid read of {num_bytes} bytes')", "b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password", "with an OS protected key (keyring) - v11 keys can", "table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info]", "jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f' ({failed_cookies} could", "the most recently used one i, paths = 0, []", "# this sometimes occurs in KDE because chrome does not", "is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message", "as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted", "logger def read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid", "value, path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with", "os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name]", "in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is", "def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self,", "comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies", "salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def", "expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from", "unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import", "v10 or not v10 - v10: AES-CBC encrypted with an", "required) return None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name,", "in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown", "logger) self._v10_key = None if password is None else self.derive_key(password)", "sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32':", "kwallet returns \"\") whereas kwallet-query # checks hasEntry. To verify", "failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts =", "keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring)", "jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally: if", "*, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password =", "using `dbus-monitor` during startup, it can be observed that chromium", "self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1 if", "SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop", "os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars:", "which keyring backend # it has chosen to use #", "isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar:", "env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return", "salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self,", "return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger)", "either v10 or not v10 - v10: AES-CBC encrypted with", "[('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer),", "pDataOut ) if not ret: logger.warning('failed to decrypt with DPAPI',", "key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag,", "self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if big_endian else", "{browser_name} without sqlite3 support. ' 'Please use a python interpreter", "'--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE,", "= [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in =", "# values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16)", "0: raise ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor", "= p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset =", "'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else", "firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without", "0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self,", "the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name =", "# and presumably searches for its key in the list.", "== 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return", "v11 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext,", "'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value,", "in the same way as KWallet, # using `dbus-monitor` during", "os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root =", "pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length)", "WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger self._v10_key =", "logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path):", "chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports", "self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return", "logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True)", "values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property", "return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce'", "jar finally: if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor,", "kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query') is None:", "printer.print = lambda _: None return printer def load_cookies(cookie_file, browser_specification,", "'unknown record field 2') domain_offset = p.read_uint() name_offset = p.read_uint()", "jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return", "https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item", "logger): # note: chrome/chromium can be run with the following", "browser profiles, take the most recently used one i, paths", "dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed to", "ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying", "return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger)", "no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength", "kwallet-query # checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\"", "this may be a bug as the intended behaviour is", "keys can be stored in various places depending on the", "if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path =", "lists all keys # and presumably searches for its key", "Storage': return item.get_secret() else: logger.error('failed to read from keyring') return", "os import shutil import struct import subprocess import sys import", "paths.append(os.path.join(curr_root, file)) return None if not paths else max(paths, key=lambda", "import Enum, auto from hashlib import pbkdf2_hmac from .aes import", "which are skipped during parsing \"\"\" if jar is None:", "password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not", "expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0", "browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def", "def read_double(self, big_endian=False): data_format = '>d' if big_endian else '<d'", "key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations,", "+= 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f'", "_decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 #", "Enum, auto from hashlib import pbkdf2_hmac from .aes import (", "-m pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE =", "if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name ==", "*line) if not cookie: failed_cookies += 1 continue elif not", "p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record", "organise keys in the same way as KWallet, # using", "None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return", "+= 1 continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie)", "file)) return None if not paths else max(paths, key=lambda path:", "kwallet-query ' 'must be installed to read from KWallet. kwallet-query", "assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password", "to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the", "encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] +=", "paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar =", "logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip()", "_LinuxKeyring.BASICTEXT: # when basic text is chosen, all cookies are", "not found. KWallet and kwallet-query ' 'must be installed to", "SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None,", "os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is", "== b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot", "cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise", "_LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\"", "cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location')", "no cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger)", "decrypt v10 cookies: no key found', only_once=True) return None #", "linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT", "Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin':", "Gnome keyring does not seem to organise keys in the", "*, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif", "'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}')", "self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version ==", "return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because", "keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name", "def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None)", "'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _", "\"\"\" Overview: Linux: - cookies are either v10 or v11", "appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave':", "elif num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes} bytes')", "and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif", "{e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain", "key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else:", "Possibly the key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext,", "+= 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11':", "SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except", "p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8", "name of the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc", "unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally: if cursor", "encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc", "'>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self):", "dbus while opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\"", "p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse", "progress_bar: for curr_root, dirs, files in os.walk(root): for file in", "= [] if browser_specification is not None: browser_name, profile, keyring", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return", "database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'],", "stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with", "enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor,", "GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def", "network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode", "from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD),", "buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB()", "'v11': 0, 'other': 0} @staticmethod def derive_key(password): # values from", "field') with _create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets):", "keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if", "auto() CINNAMON = auto() GNOME = auto() KDE = auto()", "logger.debug('password found') if stdout[-1:] == b'\\n': stdout = stdout[:-1] return", "secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies", "References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out", "date but the important parts of the database structure is", "_decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password,", "def __init__(self, ydl=None): self._ydl = ydl def debug(self, message): if", "MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else:", "return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger,", "def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size =", "sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform ==", "self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other prefixes are", "browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path)", "return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root", "= len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i:", "cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext", "to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the", "value = self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value:", "== 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON", "logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger)", "= encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10']", "xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is", "not value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if", "os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise", "only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] +=", "the key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key,", "'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles }", "for _ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar,", "same way as KWallet, # using `dbus-monitor` during startup, it", "keyring, logger): # note: chrome/chromium can be run with the", "keyring == _LinuxKeyring.BASICTEXT: # when basic text is chosen, all", "does a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet", "determined by snooping on dbus while opening the browser in", "item.get_secret() else: logger.error('failed to read from keyring') return b'' def", "column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc,", "following flags to determine which keyring backend # it has", "match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:]", "state file') return None logger.debug(f'Found local state file at \"{path}\"')", "cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from", "b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version", "not support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform:", "stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except Exception", "None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8", "_decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key,", "they are already in use (e.g. by the browser) database_copy_path", "'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir':", "_get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage',", "R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User", "= os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root", "Overview: Linux: - cookies are either v10 or v11 -", "as f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except", "def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from OSX", "def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE:", "value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date,", "\"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring:", "'cookies') secure_column = 'is_secure' if 'is_secure' in column_names else 'secure'", "os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif", "to obtain password from OSX keychain') try: proc = Popen(", "!= {expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I' if", "'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi':", "be determined by snooping on dbus while opening the browser", "xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return", "def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3]", "0x0001) p.skip(4, 'unknown record field 2') domain_offset = p.read_uint() name_offset", "= p.read_uint() p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double())", "config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None:", "if proc.returncode != 0: logger.warning('failed to read NetworkWallet') return default_wallet", "'the kwallet-query man page for details') return b'' else: if", "item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to", "by running `python3 -m pip install secretstorage`.') except Exception as", "signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in", "'rb') as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger)", "YoutubeDLCookieJar() for jar in jars: for cookie in jar: output_jar.set_cookie(cookie)", "self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self):", "6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host,", "os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path =", "(AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?',", "tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT", "os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not", "for details') return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed", "output_jar def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None,", "ppszDataDescr: human readable description of pDataIn None, # pOptionalEntropy: salt?", "cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is", "pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False", "the `secretstorage` module is not installed. ' 'Please install by", "return code {proc.returncode}. Please consult ' 'the kwallet-query man page", "if not file.isatty(): return except BaseException: return printer = MultilinePrinter(file,", "return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1", "def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations,", "= '>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def", "breakdown: {counts}') return jar finally: if cursor is not None:", "'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles =", "self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10':", "{'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl", "without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try:", "return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir):", "port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None,", "= _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe", "return network_wallet except Exception as e: logger.warning(f'exception while obtaining NetworkWallet:", "= YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger)", "Linux keyring names can be determined by snooping on dbus", "pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b'", "end of the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value,", "sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform", "jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: -", "= {'v10': 0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts", "parse Safari cookie because UTF-8 decoding failed', only_once=True) return record_size", "sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage", "'<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while", "return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies]", "are a few bytes here and there which are skipped", "encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None:", "in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc", "\"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class", "YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file = expand_path(cookie_file)", ") if not ret: logger.warning('failed to decrypt with DPAPI', only_once=True)", "except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the", "is not None and _is_path(profile): profile = os.path.expanduser(profile) return browser_name,", "ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable description", "load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification is not", "conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info =", "'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata", "record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies ==", "16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except", "ydl): cookie_jars = [] if browser_specification is not None: browser_name,", "encrypted with an OS protected key (keyring) - v11 keys", "p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length)", ".minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str,", "def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub classes')", "'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'),", "logger) self._cookie_counts = {'v10': 0, 'other': 0} @property def cookie_counts(self):", "None, # pPromptStruct: information about prompts to display 0, #", "raise NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name,", "f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)}", "__init__(self, data, logger): self._data = data self.cursor = 0 self._logger", "= os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path", "b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available", "False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not be", "DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), #", "1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger):", "R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform", "== 0: logger.debug(f'a cookies page of size {len(data)} has no", "only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result", "def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) +", "is not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if", "database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info", "cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring:", "None, # pvReserved: must be NULL None, # pPromptStruct: information", "Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout,", "class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either v10", "output_jar.filename = jar.filename return output_jar def _is_path(value): return os.path.sep in", "try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in", "protected key (keyring) - v11 keys can be stored in", "(None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not", "environment [2] Mac: - cookies are either v10 or not", "decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub classes') @property", "decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key", "browser_name == 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari':", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self):", "cookies are either v10 or v11 - v10: AES-CBC encrypted", "f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to read from", "= compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key')", "rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either", "browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts", "Local State') return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI'", "field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa:", "(AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?',", "keyring: \"{keyring}\"') if profile is not None and _is_path(profile): profile", "big_endian=False): data_format = '>I' if big_endian else '<I' return struct.unpack(data_format,", "page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor", "'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile,", "== 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if", "if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger)", "Linux: - cookies are either v10 or v11 - v10:", "about prompts to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut", "os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%')", "host, name, value, path, expiry, isSecure FROM moz_cookies') jar =", "cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1", "open(path, encoding='utf8') as f: data = json.load(f) try: base64_key =", "\"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData',", "os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata,", "sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform", "'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name':", "6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies", "stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from kwallet. Using", "so the automatic detection # will not be sufficient in", "class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING", "else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger)", "ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage`", "in ('linux', 'linux2'): config = _config_home() browser_dir = { 'brave':", "value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS:", "iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16):", "location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not", "name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar =", "b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot decrypt", "compiled with sqlite3 support') return YoutubeDLCookieJar() if profile is None:", "there are multiple browser profiles, take the most recently used", "None if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def", "if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'}", "logger.debug('using kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query') is", "password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' '", "return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name,", "wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: -", "= auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS =", "self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self,", "cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox')", "return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger =", "only_once=True) return record_size p.skip_to(record_size, 'space at the end of the", "= _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password is", "cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies')", "keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium", "is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value,", "'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin'", "auto() PANTHEON = auto() UNITY = auto() XFCE = auto()", "desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop", "searches for its key in the list. It appears that", "key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic", "we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as", "logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif", "https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc = Popen([", "write password to stdout '-a', browser_keyring_name, # match 'account' '-s',", "logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult ' 'the", "decrypt with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData)", "size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page header", "if printer: return printer printer = QuietMultilinePrinter() printer.print = lambda", "ctypes import json import os import shutil import struct import", "password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is", "self._cookie_counts = {'v10': 0, 'other': 0} @property def cookie_counts(self): return", "is required) return None assert False, f'Unknown keyring {keyring}' def", "be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera',", "not check hasEntry and instead # just tries to read", "are either v10 or v11 - v10: AES-CBC encrypted with", "os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform ==", "stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to", "= jar.filename return output_jar def _is_path(value): return os.path.sep in value", "by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn", "def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1,", "logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile, logger)", "# checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\"", "is wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError:", "to be out of date but the important parts of", "is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile,", "class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON", "to read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet", "os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not", "extract cookies from firefox without sqlite3 support. ' 'Please use", "password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password", "for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}')", "with a key which is encrypted with DPAPI - not", "item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return", "big_endian=False): data_format = '>d' if big_endian else '<d' return struct.unpack(data_format,", "= auto() UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum):", "else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies", "profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return _extract_firefox_cookies(profile,", "instead') # this sometimes occurs in KDE because chrome does", "not None: logger.error('safari does not support profiles') if sys.platform !=", "discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox')", "'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local,", "def cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes') def", "return output_jar def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name,", "browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts')", "'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return", "from datetime import datetime, timedelta, timezone from enum import Enum,", "decoding failed. Possibly the key is wrong?', only_once=True) return None", "_decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext,", "timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database", "not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def", "sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall()", "https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE = True", "sqlite3 SQLITE_AVAILABLE = True except ImportError: # although sqlite3 is", "if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not", "logger, *, keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password", "description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description)", "None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using", "code {proc.returncode}. Please consult ' 'the kwallet-query man page for", "out of date but the important parts of the database", "cookies from {browser_name} without sqlite3 support. ' 'Please use a", "_LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring", "is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'),", "installed to read from KWallet. kwallet-query should be' 'included in", "def _extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari does", "if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no key", "None if password is None else self.derive_key(password) self._cookie_counts = {'v10':", "raise FileNotFoundError(f'could not find firefox cookies database in {search_root}') logger.debug(f'Extracting", "from safari') return jar class ParserError(Exception): pass class DataParser: def", "sqlite databases if they are already in use (e.g. by", "'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop", "prompts to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut )", "progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies:", "profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser:", "_extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot", "= _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger):", "= raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other']", "def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used to", "from kwallet. Using empty string instead') # this sometimes occurs", "is the same - there are a few bytes here", "p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint()", "= [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor def", "failed_cookies > 0: failed_message = f' ({failed_cookies} could not be", "+= 1 # any other prefix means the data is", "be sufficient in all cases. keyring = _LinuxKeyring[keyring] if keyring", "auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\"", "logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger):", "# dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed", "= b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return", "class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def debug(self,", "_parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size in page_sizes:", "_merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name ==", "= compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'),", "cookies are either v10 or not v10 - v10: AES-GCM", "the `secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS =", "doesn't matter here. return b'' else: logger.debug('password found') if stdout[-1:]", "keys in the same way as KWallet, # using `dbus-monitor`", "if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database')", "class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger password", "@staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password,", "= False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is", "= _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if", "'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def", "keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT:", "name = name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted", "in between pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data,", "stdout except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return", "aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses", "= None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name,", "sqlite3 support') return YoutubeDLCookieJar() if profile is None: search_root =", "record_size p.skip_to(record_size, 'space at the end of the record') cookie", "'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env:", "encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version ==", "logger.debug(f'Found local state file at \"{path}\"') with open(path, encoding='utf8') as", "_LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME", "= encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 if", "this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. #", "if profile is None: search_root = config['browser_dir'] elif _is_path(profile): search_root", "for i, (host, name, value, path, expiry, is_secure) in enumerate(table):", "cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0", "end of input') data = self._data[self.cursor:end] self.cursor = end return", "is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile", "self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def", "get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux', 'linux2'):", "not ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return None", "{num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description)", "tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies')", "p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for", "0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count =", "record_size = p.read_uint() p.skip(4, 'unknown record field 1') flags =", "_is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else", "raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key,", "jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto()", "== 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application", "- https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out of", "return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] +=", "if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no key", "the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try:", "as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir)", "to read'): logger.debug('failed to read password from kwallet. Using empty", "_find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not", "either v10 or v11 - v10: AES-CBC encrypted with a", "determine which keyring backend # it has chosen to use", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto()", "_get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path", "search_root = config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] =", "_LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in", "page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for", "encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password,", "( 'as the `secretstorage` module is not installed. ' 'Please", "def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for", "failed', only_once=True) return record_size p.skip_to(record_size, 'space at the end of", "if sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir =", "Using empty string instead') # this sometimes occurs in KDE", "result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): #", "ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format", "v11 - v10: AES-CBC encrypted with a fixed key -", "6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger)", "logger.error('kwallet-query command not found. KWallet and kwallet-query ' 'must be", "find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"')", "'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'),", "desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER:", "= _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop =", "\"{filename}\": {i: 6d} files searched') if file == filename: paths.append(os.path.join(curr_root,", "linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name", "sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is", "& 0x0001) p.skip(4, 'unknown record field 2') domain_offset = p.read_uint()", "}[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir", "# https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for", "it is possible to compile python without # sqlite support.", "SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module", "logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar class ParserError(Exception):", "f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr", "== filename: paths.append(os.path.join(curr_root, file)) return None if not paths else", "decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version", "AES-GCM encrypted with a key which is encrypted with DPAPI", "skipped during parsing \"\"\" if jar is None: jar =", "'--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr =", "0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table =", "in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave':", "stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as e:", "'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'),", "browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key", "lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if", "raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag", "'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi':", "= '>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value):", "= unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed", "OTHER = auto() CINNAMON = auto() GNOME = auto() KDE", "to read the value (which kwallet returns \"\") whereas kwallet-query", "elif desktop_session is not None: if desktop_session in ('mate', 'gnome'):", "buffer = [] while True: c = self.read_bytes(1) if c", "shutil import struct import subprocess import sys import tempfile from", "expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie", "encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies", "num_bytes): if num_bytes < 0: raise ParserError(f'invalid read of {num_bytes}", "of pDataIn None, # pOptionalEntropy: salt? None, # pvReserved: must", "'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session", "if password is None else self.derive_key(password) self._cookie_counts = {'v10': 0,", "json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key", "import sqlite3 SQLITE_AVAILABLE = True except ImportError: # although sqlite3", "basic text is chosen, all cookies are stored as v10", "= decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None return", "'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local", "value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc,", "auto() GNOME = auto() KDE = auto() PANTHEON = auto()", "# the Gnome keyring does not seem to organise keys", "return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data,", "data_format = '>d' if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0]", "e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger):", "({failed_cookies} could not be decrypted)' else: failed_message = '' logger.info(f'Extracted", "hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7,", "= f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from", "['security', 'find-generic-password', '-w', # write password to stdout '-a', browser_keyring_name,", "in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE", "self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0,", "is used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to the following", "from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox", "on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger,", "because the MAC check failed. Possibly the key is wrong?',", "' 'Please install by running `python3 -m pip install secretstorage`.')", "[2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must", "page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class", "= self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected value: {value}", "if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop", "for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')", "tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column =", "self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key", "SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON =", "ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor + num_bytes", "wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger):", "in the list. It appears that we must do the", "key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version", "return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif", "try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path,", "a fixed key - v11: AES-CBC encrypted with an OS", "except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None", "obtain password from OSX keychain') try: proc = Popen( ['security',", "failed. Possibly the key is wrong?', only_once=True) return None try:", "sometimes occurs in KDE because chrome does not check hasEntry", "encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger", "all keys # and presumably searches for its key in", "= self.cursor + num_bytes if end > len(self._data): raise ParserError('reached", "== _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return", "else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format =", "encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid", "firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with", "version = encrypted_value[:3] ciphertext = encrypted_value[3:] if version == b'v10':", "{proc.returncode}. Please consult ' 'the kwallet-query man page for details')", "for curr_root, dirs, files in os.walk(root): for file in files:", "pPromptStruct: information about prompts to display 0, # dwFlags ctypes.byref(blob_out)", "cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with", "if failed_cookies > 0: failed_message = f' ({failed_cookies} could not", "if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet and", "else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = []", "profile) else: logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir']", "module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome',", "return YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir() elif", "data' stored as plaintext Windows: - cookies are either v10", "if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3", "self._ydl = ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def", "databases if they are already in use (e.g. by the", "None: logger.error('could not find local state file') return None logger.debug(f'Found", "Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\"", "else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from", "# just tries to read the value (which kwallet returns", "DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record field 1')", "else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does", "return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1", "= 0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count", "default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet", "return None if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime)", "- v10: AES-GCM encrypted with a key which is encrypted", "dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet", "key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\"", "'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'),", "discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: -", "printer = logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter()", "'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger:", "= bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if", "default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from", "https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir", "safari') return jar class ParserError(Exception): pass class DataParser: def __init__(self,", "sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform ==", "files searched') if file == filename: paths.append(os.path.join(curr_root, file)) return None", "The name of the wallet used to store network passwords.", "stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout =", "browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles':", "SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. '", "find safari cookies database') with open(cookies_path, 'rb') as f: cookies_data", "R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application", "hasEntry and instead # just tries to read the value", "be observed that chromium lists all keys # and presumably", "logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name}", "\"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by sub", "_process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key =", "def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars: for", "== 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin'", "used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a", "if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' #", "an OS protected key (keyring) and more key derivation iterations", "discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None,", "pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def", "elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform ==", "YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count =", "printer: return printer printer = QuietMultilinePrinter() printer.print = lambda _:", "more key derivation iterations than linux - not v10: 'old", "else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self,", "Safe Storage': return item.get_secret() else: logger.error('failed to read from keyring')", "p.skip(4, 'unknown record field 2') domain_offset = p.read_uint() name_offset =", "in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies", "logger.debug('using find-generic-password to obtain password from OSX keychain') try: proc", "if value != expected_value: raise ParserError(f'unexpected value: {value} != {expected_value}", "version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None:", "= QuietMultilinePrinter() printer.print = lambda _: None return printer def", "'<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d'", "a flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will not", "random password and store # it, but that doesn't matter", "raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self, big_endian=False):", "[2] Mac: - cookies are either v10 or not v10", "found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length =", "return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None", "chosen to use # chromium --enable-logging=stderr --v=1 2>&1 | grep", "not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'):", "jar.filename is not None: output_jar.filename = jar.filename return output_jar def", "cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor =", "16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length]", "KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented by", "== b'\\n': stdout = stdout[:-1] return stdout except Exception as", "= _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size in", "if there are multiple browser profiles, take the most recently", "in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:", "initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'}", "ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData',", "'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find", "# any other prefix means the data is DPAPI encrypted", "0: raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset,", "or when --no-progress is used if not self._ydl or self._ydl.params.get('noprogress')", "version breakdown: {counts}') return jar finally: if cursor is not", "_get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring", "while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using", "return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return", "_get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic text", "(keyring) and more key derivation iterations than linux - not", "pvReserved: must be NULL None, # pPromptStruct: information about prompts", "buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping", "self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name,", "key - v11: AES-CBC encrypted with an OS protected key", "v10 cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext,", "multiple browser profiles, take the most recently used one i,", "stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout", "try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset)", "'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge':", "= stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as", "is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag,", "encrypted with an OS protected key (keyring) and more key", "raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform", "class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger = logger self._v10_key", "ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce,", "self._data = data self.cursor = 0 self._logger = logger def", "return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop", "ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check", "len(table) for i, (host, name, value, path, expiry, is_secure) in", "kwallet package for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger)", "= auto() PANTHEON = auto() UNITY = auto() XFCE =", "compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path,", "cookies database') with open(cookies_path, 'rb') as f: cookies_data = f.read()", "the key is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger):", "_extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not", "from KWallet. kwallet-query should be' 'included in the kwallet package", "not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file,", "See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE =", "can be stored in various places depending on the activate", "b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password',", "not v10 - v10: AES-CBC encrypted with an OS protected", "browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = {", "with DPAPI - not v10: encrypted with DPAPI Sources: -", "desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME", "NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"')", "verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome.", "initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie", "except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding", "self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if", "+ num_bytes if end > len(self._data): raise ParserError('reached end of", "= None if password is None else self.derive_key(password) self._cookie_counts =", "ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path,", "secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON", "bytes here and there which are skipped during parsing \"\"\"", "def _is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None):", "cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value,", "while opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\"", "return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else:", "table = cursor.fetchall() total_cookie_count = len(table) for i, line in", "'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge':", "QuietMultilinePrinter() printer.print = lambda _: None return printer def load_cookies(cookie_file,", "not None and _is_path(profile): profile = os.path.expanduser(profile) return browser_name, profile,", "{ 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles", "= env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop =", "return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes", "logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir'] cookie_database_path =", "config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None", "1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger", "intended behaviour is to generate a random password and store", "_LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop ==", "= logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0,", "try: if not file.isatty(): return except BaseException: return printer =", "only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96", "path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path is None:", "in files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d}", "logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector))", "if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl:", "cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if", "= value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value and", "None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return", "in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page of", "'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode", "obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query", "\"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this may be", "# note: chrome/chromium can be run with the following flags", "text is chosen, all cookies are stored as v10 (so", "table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename,", "network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception", "if profile is not None: logger.error('safari does not support profiles')", "'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc", "encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key", "'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles", "num_bytes < 0: raise ParserError(f'invalid read of {num_bytes} bytes') end", "compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen,", "# write password to stdout '-a', browser_keyring_name, # match 'account'", "self._logger) else: self._cookie_counts['other'] += 1 # any other prefix means", "To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting", "0, [] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files", "tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path,", "({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip of", "plaintext Windows: - cookies are either v10 or not v10", "https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be out of date", "counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}')", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8 # boringssl", "logger.warning('Cannot extract cookies from firefox without sqlite3 support. ' 'Please", "there are a few bytes here and there which are", "keyring backend # it has chosen to use # chromium", "KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS", "of size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page", "' 'must be installed to read from KWallet. kwallet-query should", "'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name]", "name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure,", "_merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in jars: for cookie", "self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor):", "_get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from OSX keychain')", "browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if", "profile is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root =", "'--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr", "proc.returncode != 0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please", "os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database') with open(cookies_path,", "not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies database') with", "skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'):", "expected_value, message): value = self.read_bytes(len(expected_value)) if value != expected_value: raise", "keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"')", "os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform == 'darwin': appdata =", "config['supports_profiles'] else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile)", "browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if", "os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform:", "None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from", "\"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception while obtaining", "with return code {proc.returncode}. Please consult ' 'the kwallet-query man", "domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path =", "of {num_bytes} bytes') end = self.cursor + num_bytes if end", "search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root", "= auto() GNOME = auto() KDE = auto() PANTHEON =", "_find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not", "_LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID'", "jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall()", "data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local State') return", "were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor):", "def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox':", "is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie =", "path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies =", "number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)]", "key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key,", "read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid read of", "return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if", "'Please install by running `python3 -m pip install secretstorage`.') except", "= encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 return", "SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome", "support. ' 'Please use a python interpreter compiled with sqlite3", "from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3", "decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None return is_encrypted,", "else: self._cookie_counts['other'] += 1 # other prefixes are considered 'old", "\"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if", "[] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in", "password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11':", "nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any other", "activate desktop environment [2] Mac: - cookies are either v10", "import tempfile from datetime import datetime, timedelta, timezone from enum", "{i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:],", "'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def", "cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root,", "raise ParserError(f'invalid read of {num_bytes} bytes') end = self.cursor +", "grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the", "keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password", "# pDataOut ) if not ret: logger.warning('failed to decrypt with", "'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if", "logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True)", "self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any", "if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}')", "'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif", "self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with a print", "jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears", "p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari", "password and store # it, but that doesn't matter here.", "'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else", "'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'),", "keyring=None): self._logger = logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name,", "{browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without", "salt? None, # pvReserved: must be NULL None, # pPromptStruct:", "_config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'),", "the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which", "cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor,", "= profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else:", "the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8')", "} def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}')", "as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage`", "domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie)", "- not v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/", "a bug as the intended behaviour is to generate a", "v11: AES-CBC encrypted with an OS protected key (keyring) -", "package for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try:", "logger): logger.debug('using kwallet-query to obtain password from kwallet') if shutil.which('kwallet-query')", "[p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data,", "= DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes", "DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes =", "KWalletDBus::NetworkWallet which does a dbus call to the following function:", "to parse Safari cookie because UTF-8 decoding failed', only_once=True) return", "c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes,", "= logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter() printer.print", "iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value):", "= sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA", "parsing \"\"\" if jar is None: jar = YoutubeDLCookieJar() page_sizes,", "return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger =", "= \"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception while", "= ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag =", "cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find", "for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not None:", "desktop environment [2] Mac: - cookies are either v10 or", "\"\"\" OTHER = auto() CINNAMON = auto() GNOME = auto()", "== 'firefox': return _extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return", "None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p", "match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE,", "buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn", "'-w', # write password to stdout '-a', browser_keyring_name, # match", "num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes", "_parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None:", "_firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(),", "ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are either v10 or", "DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr:", "'other': 0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value):", "except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the MAC", "field 2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset =", "logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try:", "\"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor", "kNonceLength nonce_length = 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN", "is not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def", "encrypted with DPAPI - not v10: encrypted with DPAPI Sources:", "most recently used one i, paths = 0, [] with", "decryption is not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor):", "if desktop_session is not None and 'gnome-fallback' in desktop_session: return", "return None assert False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger):", "'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata,", "not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl),", "{browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox') if not", "description of pDataIn None, # pOptionalEntropy: salt? None, # pvReserved:", "logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies", "= not value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value)", "python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if profile", "read of {num_bytes} bytes') end = self.cursor + num_bytes if", "firefox without sqlite3 support. ' 'Please use a python interpreter", "in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie =", "path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size", "'unknown record field 1') flags = p.read_uint() is_secure = bool(flags", "for its key in the list. It appears that we", "note: chrome/chromium can be run with the following flags to", "'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', 'opera':", "stored as plaintext Windows: - cookies are either v10 or", "def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise", "_LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is", "domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None,", "end > len(self._data): raise ParserError('reached end of input') data =", "self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException: return printer", "return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name):", "there which are skipped during parsing \"\"\" if jar is", "logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring", "UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h", "chrome/chromium can be run with the following flags to determine", "= _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1 continue", "pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size", "raise NotImplementedError(f'Chrome cookie decryption is not supported on this platform:", "logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if path is", "any other prefix means the data is DPAPI encrypted #", "which is encrypted with DPAPI - not v10: encrypted with", "'keyring_name': keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name,", "chrome. # this may be a bug as the intended", "import ctypes import json import os import shutil import struct", "although sqlite3 is part of the standard library, it is", "True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as", "printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def", "a random password and store # it, but that doesn't", "of date but the important parts of the database structure", "None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod", "{expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I' if big_endian", "v11 keys can be stored in various places depending on", "which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class", "import struct import subprocess import sys import tempfile from datetime", "list. It appears that we must do the same. #", "cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory =", "or v11 - v10: AES-CBC encrypted with a fixed key", "def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this", "be installed to read from KWallet. kwallet-query should be' 'included", "kwallet. Using empty string instead') # this sometimes occurs in", "0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult '", "this data appears to be out of date but the", "{'v10': 0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password): #", "os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local,", "= YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars)", "({message})') def read_uint(self, big_endian=False): data_format = '>I' if big_endian else", "Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send',", "except ImportError: # although sqlite3 is part of the standard", "UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at the", "pDataIn None, # ppszDataDescr: human readable description of pDataIn None,", "cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length =", "= logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger)", "decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space at the end", "p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path", "class DataParser: def __init__(self, data, logger): self._data = data self.cursor", "cursor.fetchall() total_cookie_count = len(table) for i, line in enumerate(table): progress_bar.print(f'Loading", "os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera", "decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:", "FileNotFoundError('could not find safari cookies database') with open(cookies_path, 'rb') as", "sys import tempfile from datetime import datetime, timedelta, timezone from", "bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def", "CINNAMON = auto() GNOME = auto() KDE = auto() PANTHEON", "browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from", "= auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend", "logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring =", "proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read NetworkWallet') return", "try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed", "_: None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars =", "return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def", "'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class", "appears to be out of date but the important parts", "SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is not installed.", "ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor = end", "- v10: AES-CBC encrypted with an OS protected key (keyring)", "('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin':", "path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)}", "self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try:", "None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK):", "def __init__(self, browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root,", "check hasEntry and instead # just tries to read the", "with a fixed key - v11: AES-CBC encrypted with an", "encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext,", "SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3 support. '", "password from kwallet. Using empty string instead') # this sometimes", "'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform ==", "_creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain =", "hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while", "compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path,", "# noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name", "continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies", "(so no keyring password is required) return None assert False,", "comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\"", "import sys import tempfile from datetime import datetime, timedelta, timezone", "elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session:", "name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure,", "a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\"", "def read_bytes(self, num_bytes): if num_bytes < 0: raise ParserError(f'invalid read", "+= 1 if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies:", "OS protected key (keyring) - v11 keys can be stored", "'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] ==", "self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari", "v10: AES-CBC encrypted with an OS protected key (keyring) and", "| {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl =", "ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return None result", "same - there are a few bytes here and there", "values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property", "logger.progress_bar() if printer: return printer printer = QuietMultilinePrinter() printer.print =", "- this data appears to be out of date but", "shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet and kwallet-query", "authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else:", "raise FileNotFoundError('could not find safari cookies database') with open(cookies_path, 'rb')", "xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is not None", "return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic", "row in table_info] def _find_most_recently_used_file(root, filename, logger): # if there", "try: import sqlite3 SQLITE_AVAILABLE = True except ImportError: # although", "various places depending on the activate desktop environment [2] Mac:", "name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure,", "record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages')", "data_format = '>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0]", "# while starting chrome. # this may be a bug", "= DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in),", "def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if", "`secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave',", "return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER =", "from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name}", "not v10 - v10: AES-GCM encrypted with a key which", "' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return", "_LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring", "skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset -", "message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies]", "desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment ==", "logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies", "open sqlite databases if they are already in use (e.g.", "= lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger):", "raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger) else: self._cookie_counts['other'] +=", "authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except", "AES-CBC encrypted with an OS protected key (keyring) - v11", "data, logger): self._data = data self.cursor = 0 self._logger =", "None: output_jar.filename = jar.filename return output_jar def _is_path(value): return os.path.sep", "logger, *, keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name,", "encrypted_value): raise NotImplementedError('Must be implemented by sub classes') @property def", "platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux',", "None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger)", "key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce,", "of the standard library, it is possible to compile python", "_parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger) record_size = p.read_uint()", "cookie_jars = [] if browser_specification is not None: browser_name, profile,", "__init__(self, browser_root, logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger)", "else: logger.error('failed to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name,", "NotImplementedError(f'Chrome cookie decryption is not supported on this platform: {sys.platform}')", "when basic text is chosen, all cookies are stored as", "from OSX keychain') try: proc = Popen( ['security', 'find-generic-password', '-w',", "'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge' if sys.platform", "expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as", "def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a", "in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in", "self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot decrypt v11", "the value (which kwallet returns \"\") whereas kwallet-query # checks", "+= 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if", "profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file =", "python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False", "if profile is None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root", "supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name,", "appears that we must do the same. # https://github.com/jaraco/keyring/issues/556 with", "stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query", "if config['supports_profiles'] else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'],", "_decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11'] += 1", "b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is None: self._logger.warning('cannot decrypt", "network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name}", "other prefix means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc", "{i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not", "if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif", "noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name =", "os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux", "'-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'], #", "1 continue elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if", "not seem to organise keys in the same way as", "jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return", "range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p =", "wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed", "obtain password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command", "DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext)", "are either v10 or not v10 - v10: AES-GCM encrypted", "logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if", "= os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local,", "compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return", "--enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium supports a", "encrypted key in Local State') return None encrypted_key = compat_b64decode(base64_key)", "= compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'),", "auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\"", "value != expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})')", "cookies: no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc #", "\"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger,", "= p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if", "= YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:],", "return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop", "not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does", "used one i, paths = 0, [] with _create_progress_bar(logger) as", "= True except ImportError: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = (", "return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1", "https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_ =", "Data'), }[browser_name] elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support')", "_parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported", "'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported", "{message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer", "KeyError: logger.error('no encrypted key in Local State') return None encrypted_key", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto() GNOME", "== 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin'", "implemented by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be", "password is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other':", "_LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop ==", "and more key derivation iterations than linux - not v10:", "is not None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME", "= _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies')", "'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif", "p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field 3') expiration_date", "it has chosen to use # chromium --enable-logging=stderr --v=1 2>&1", "as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i:", "return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not", "key in Local State') return None encrypted_key = compat_b64decode(base64_key) prefix", "kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found. KWallet", ".utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE", "python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config =", "'old data' stored as plaintext Windows: - cookies are either", "p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00',", "proc.returncode != 0: logger.warning('failed to read NetworkWallet') return default_wallet else:", "else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts", "_find_most_recently_used_file(browser_root, 'Local State', logger) if path is None: logger.error('could not", "{search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor", "SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self,", "def read_uint(self, big_endian=False): data_format = '>I' if big_endian else '<I'", "= auto() CINNAMON = auto() GNOME = auto() KDE =", "profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite',", "= _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset)", "_get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be run with", "os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local,", "p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date =", "authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because", "self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def", "part of the standard library, it is possible to compile", "= _firefox_browser_dir() elif _is_path(profile): search_root = profile else: search_root =", "// 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext", "struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if big_endian", "stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed", "os.walk(root): for file in files: i += 1 progress_bar.print(f'Searching for", "config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support", "'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ],", "'as the `secretstorage` module is not installed. ' 'Please install", "if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout except", "password is required) return None assert False, f'Unknown keyring {keyring}'", "Mac: - cookies are either v10 or not v10 -", "0} @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version", "+ timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook',", "= CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None):", "with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT", "== 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE", "os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi':", "State') return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if", "not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not", "path is None: logger.error('could not find local state file') return", "It appears that we must do the same. # https://github.com/jaraco/keyring/issues/556", "port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None,", "= auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment", "is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux',", "and presumably searches for its key in the list. It", "_get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from kwallet') if", "domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={})", "else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes > 0:", "elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon':", "_mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain", "logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path", "i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched')", "if file == filename: paths.append(os.path.join(curr_root, file)) return None if not", "no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger)", "end return data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value))", "bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure'", "plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8", "rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally:", "be' 'included in the kwallet package for your distribution') return", "raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can be", "message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if", "1 if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no", "description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc)", "does not support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root,", "cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as", "appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'),", "LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger", "= _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else:", "jar in jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename", "decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}')", "UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed.", "cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True,", "import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE = False", "SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not be initialized.", "= config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile)", "elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not", "a few bytes here and there which are skipped during", "--v=1 2>&1 | grep key_storage_ # Chromium supports a flag:", "automatic detection # will not be sufficient in all cases.", "# https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config = _config_home()", "None, # pOptionalEntropy: salt? None, # pvReserved: must be NULL", "cookies database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp')", "jar class ParserError(Exception): pass class DataParser: def __init__(self, data, logger):", "progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name,", "_parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data,", "= 0, [] with _create_progress_bar(logger) as progress_bar: for curr_root, dirs,", "standard library, it is possible to compile python without #", "not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3 support.", "'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring", "filename, logger): # if there are multiple browser profiles, take", "_decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is not None:", "b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if num_bytes >", "for jar in jars: for cookie in jar: output_jar.set_cookie(cookie) if", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile", "jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment", "is to generate a random password and store # it,", "--no-progress is used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'):", "progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, (host,", "self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None", "progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length", "of the record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None,", "chrome does not check hasEntry and instead # just tries", "logger) elif keyring == _LinuxKeyring.BASICTEXT: # when basic text is", "for row in table_info] def _find_most_recently_used_file(root, filename, logger): # if", "can be run with the following flags to determine which", "sqlite3 support. ' 'Please use a python interpreter compiled with", "{browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown:", "not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path,", "depending on the activate desktop environment [2] Mac: - cookies", "return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length):", "logger.error('safari does not support profiles') if sys.platform != 'darwin': raise", "import contextlib import ctypes import json import os import shutil", "browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match", "self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message,", "not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error']", "not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from:", "{desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment", "= _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try: p.skip_to(domain_offset) domain = p.read_cstring()", "None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key,", "aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt cookie", "p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint()", "i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted,", "if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed", "number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)]", "proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout", "{secure_column} FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies", "wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does", "# other prefixes are considered 'old data' which were stored", "DesktopEnvironment \"\"\" OTHER = auto() CINNAMON = auto() GNOME =", "domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={})", "# kNonceLength nonce_length = 96 // 8 # boringssl #", "_parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h", "logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError:", "function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc =", "stdout except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return", "if proc.returncode != 0: logger.error(f'kwallet-query failed with return code {proc.returncode}.", "or not v10 - v10: AES-CBC encrypted with an OS", "if not cookie: failed_cookies += 1 continue elif not is_encrypted:", "logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger)", "in the kwallet package for your distribution') return b'' network_wallet", "'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name,", "cookies from firefox') return jar finally: if cursor is not", "of input') data = self._data[self.cursor:end] self.cursor = end return data", "not find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies from:", "not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0:", "cookie decryption is not supported on this platform: {sys.platform}') class", "None: logger.error('kwallet-query command not found. KWallet and kwallet-query ' 'must", "'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if", "_find_most_recently_used_file(root, filename, logger): # if there are multiple browser profiles,", "self.cursor = 0 self._logger = logger def read_bytes(self, num_bytes): if", "raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'):", "= raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext,", "Edge' if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if", "> 0: failed_message = f' ({failed_cookies} could not be decrypted)'", "in table_info] def _find_most_recently_used_file(root, filename, logger): # if there are", "does not support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported", "desktop_session is not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME", "= host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path =", "and instead # just tries to read the value (which", "1 # other prefixes are considered 'old data' which were", "= cursor.fetchall() total_cookie_count = len(table) for i, line in enumerate(table):", "the end of the record') cookie = compat_cookiejar_Cookie( version=0, name=name,", "= False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError:", "config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else: if config['supports_profiles']:", "logger): if profile is not None: logger.error('safari does not support", "startup, it can be observed that chromium lists all keys", "can be observed that chromium lists all keys # and", "of the database structure is the same - there are", "= 0 self._logger = logger def read_bytes(self, num_bytes): if num_bytes", "because chrome does not check hasEntry and instead # just", "detection # will not be sufficient in all cases. keyring", "elif version == b'v11': self._cookie_counts['v11'] += 1 if self._v11_key is", "('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE", "'--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill()", "and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is", "is not installed. ' 'Please install by running `python3 -m", "_LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP',", "with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor =", "either v10 or not v10 - v10: AES-GCM encrypted with", "def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux',", "database') with open(cookies_path, 'rb') as f: cookies_data = f.read() jar", "jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies", "file at \"{path}\"') with open(path, encoding='utf8') as f: data =", "stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1]", "import subprocess import sys import tempfile from datetime import datetime,", "logger): logger.debug('using find-generic-password to obtain password from OSX keychain') try:", "desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING", "env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not", "derivation iterations than linux - not v10: 'old data' stored", "stdout = stdout[:-1] return stdout except Exception as e: logger.warning(f'exception", "value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name =", "from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat", "support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None:", "col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret() else:", "NULL None, # pPromptStruct: information about prompts to display 0,", "e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger):", "port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None,", "dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome',", "protected key (keyring) and more key derivation iterations than linux", "end = self.cursor + num_bytes if end > len(self._data): raise", "for your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc", "not be sufficient in all cases. keyring = _LinuxKeyring[keyring] if", "plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError:", "printer printer = QuietMultilinePrinter() printer.print = lambda _: None return", "keyring does not seem to organise keys in the same", "raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS):", "v10 - v10: AES-GCM encrypted with a key which is", "logger): self._logger = logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts =", "file') return None logger.debug(f'Found local state file at \"{path}\"') with", "browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if keyring", "cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from", "from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def", "proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name}", "ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None):", "elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported", "elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in", "header field') with _create_progress_bar(logger) as progress_bar: for i, record_offset in", "(which kwallet returns \"\") whereas kwallet-query # checks hasEntry. To", "not file.isatty(): return except BaseException: return printer = MultilinePrinter(file, preserve_output=False)", "('linux', 'linux2'): config = _config_home() browser_dir = { 'brave': os.path.join(config,", "= os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles') search_root", "None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session", "sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies')", "only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message): if self._ydl:", "def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self,", "else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in", "cookie (AES-GCM) because the MAC check failed. Possibly the key", "platform: {sys.platform}') # Linux keyring names can be determined by", "keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge':", "return p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as progress_bar:", "desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET", "is possible to compile python without # sqlite support. See:", "R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'),", "iterations than linux - not v10: 'old data' stored as", "'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform", "'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming", "not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return", "and kwallet-query ' 'must be installed to read from KWallet.", "== _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: #", "'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring,", "def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config", "message: printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger,", "None: search_root = config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir']", "# cannot open sqlite databases if they are already in", "other prefixes are considered 'old data' which were stored as", "return file = self._ydl._out_files['error'] try: if not file.isatty(): return except", "in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p", "or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if", "logger.debug('failed to read password from kwallet. Using empty string instead')", "sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir", "logger.error('could not find local state file') return None logger.debug(f'Found local", "= ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret", "__init__(self, ydl=None): self._ydl = ydl def debug(self, message): if self._ydl:", "self.cursor + num_bytes if end > len(self._data): raise ParserError('reached end", "_get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used to store", "None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return", "8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext =", "running `python3 -m pip install secretstorage`.') except Exception as _err:", "not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile", "cookies_data = f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies", "'>I' if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self,", "_open_database_copy(database_path, tmpdir): # cannot open sqlite databases if they are", "= self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self, expected_value,", "Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def", "conn.cursor() def _get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8')", "= auto() KDE = auto() PANTHEON = auto() UNITY =", "database in {search_root}') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as", "self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self, expected_value, message):", "keyring names can be determined by snooping on dbus while", "cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name} cookies database", "data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no", "return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}')", "p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset)", "ciphertext = encrypted_value[3:] if version == b'v10': self._cookie_counts['v10'] += 1", "is None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger)", "WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is not supported", "= DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger)", "all cookies are stored as v10 (so no keyring password", "self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not file.isatty(): return", "- self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp):", "be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *,", "_firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform", "at the end of the record') cookie = compat_cookiejar_Cookie( version=0,", "return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar()", "if not ret: logger.warning('failed to decrypt with DPAPI', only_once=True) return", "desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME':", "ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can be determined", "following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet = 'kdewallet' try: proc", "Windows: - cookies are either v10 or not v10 -", "number_of_cookies == 0: logger.debug(f'a cookies page of size {len(data)} has", ".compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from", "return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format = '>d' if", "return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite", "import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE =", "not print to files/pipes, loggers, or when --no-progress is used", "display 0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if not", "check failed. Possibly the key is wrong?', only_once=True) return None", "are either v10 or not v10 - v10: AES-CBC encrypted", "only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata", "password to stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name}", "readable description of pDataIn None, # pOptionalEntropy: salt? None, #", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self):", "'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\"", "'' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted']", "f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain", "with _create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading", "value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value and encrypted_value", "is part of the standard library, it is possible to", "your distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc =", "ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in", "{num_bytes} bytes') end = self.cursor + num_bytes if end >", "= _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could", "way as KWallet, # using `dbus-monitor` during startup, it can", "desktop_session is not None: if desktop_session in ('mate', 'gnome'): return", "else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return", "than linux - not v10: 'old data' stored as plaintext", "'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor,", "CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def __init__(self, ydl=None): self._ydl", "- there are a few bytes here and there which", "if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read password from kwallet.", "in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between", "None and _is_path(profile): profile = os.path.expanduser(profile) return browser_name, profile, keyring", "self._logger) else: self._cookie_counts['other'] += 1 # other prefixes are considered", "(AES-GCM) because the MAC check failed. Possibly the key is", "_err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module", "support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import secretstorage SECRETSTORAGE_AVAILABLE", "if browser_specification is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification)", "else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column}", "= ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME',", "from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar,", "call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html Wallet::NetworkWallet \"\"\" default_wallet =", "with the following flags to determine which keyring backend #", "total_cookie_count = len(table) for i, (host, name, value, path, expiry,", "file = self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException:", "progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if file ==", "0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return", "], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode !=", "@property def cookie_counts(self): raise NotImplementedError('Must be implemented by sub classes')", "os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User", "xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return", "{error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local", "v10: AES-CBC encrypted with a fixed key - v11: AES-CBC", "YoutubeDLCookieJar() if profile is None: search_root = _firefox_browser_dir() elif _is_path(profile):", "'Local State', logger) if path is None: logger.error('could not find", "== 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return {", "raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path):", "keyring=keyring)) if cookie_file is not None: cookie_file = expand_path(cookie_file) jar", "in various places depending on the activate desktop environment [2]", "'old data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return", "return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 //", "i, (host, name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading", "on dbus while opening the browser in KDE: # dbus-monitor", "def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page", "value and encrypted_value if is_encrypted: value = decryptor.decrypt(encrypted_value) if value", "== 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON", "self._cookie_counts['other'] += 1 # other prefixes are considered 'old data'", "= cursor.fetchall() total_cookie_count = len(table) for i, (host, name, value,", "plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root,", "profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name}", "Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill()", "return jar finally: if cursor is not None: cursor.connection.close() def", "logger.debug(f'cookie version breakdown: {counts}') return jar finally: if cursor is", "'must be installed to read from KWallet. kwallet-query should be'", "or not v10 - v10: AES-GCM encrypted with a key", "expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value =", "places depending on the activate desktop environment [2] Mac: -", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment:", "= _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not", "version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path),", "_get_column_names(cursor, table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row", "keychain') try: proc = Popen( ['security', 'find-generic-password', '-w', # write", "= os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path", "Popen( ['security', 'find-generic-password', '-w', # write password to stdout '-a',", "path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}')", "}[browser_name] elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming =", "only_once=True) return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to", "_LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def", "xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop", "hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return printer printer", "KWallet. kwallet-query should be' 'included in the kwallet package for", "= _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is None", "as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if", "BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc", "record') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain,", "pDataIn None, # pOptionalEntropy: salt? None, # pvReserved: must be", "not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if", "database structure is the same - there are a few", "not None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif", "logger) record_size = p.read_uint() p.skip(4, 'unknown record field 1') flags", "# ppszDataDescr: human readable description of pDataIn None, # pOptionalEntropy:", "= self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c)", "6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie:", "NotImplementedError('Must be implemented by sub classes') @property def cookie_counts(self): raise", "== b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot", "is None: self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True)", "in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop ==", "consult ' 'the kwallet-query man page for details') return b''", "that doesn't matter here. return b'' else: logger.debug('password found') if", "else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium',", "import MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path", "ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:]", "is not None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else:", "encrypted with a key which is encrypted with DPAPI -", "path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\"", "self.cursor = end return data def expect_bytes(self, expected_value, message): value", "return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\"", "in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie(", "_process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies += 1 continue elif", "try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM)", "store # it, but that doesn't matter here. return b''", "== 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir =", "key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt", "return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext", "is wrong?', only_once=True) return None def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References:", "UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed.", "FileNotFoundError(f'could not find firefox cookies database in {search_root}') logger.debug(f'Extracting cookies", "CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS =", "_LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring =", "keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try: cursor", "host_key = host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path", "def read_cstring(self): buffer = [] while True: c = self.read_bytes(1)", "contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in col.get_all_items():", "for \"{filename}\": {i: 6d} files searched') if file == filename:", "_open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column", "not v10: 'old data' stored as plaintext Windows: - cookies", "cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host),", "behaviour is to generate a random password and store #", "= self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None", "subprocess import sys import tempfile from datetime import datetime, timedelta,", "printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}',", "skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1,", "if cookie_database_path is None: raise FileNotFoundError(f'could not find firefox cookies", "{ 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'),", "to read password from kwallet. Using empty string instead') #", "v10 (so no keyring password is required) return None assert", "def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer:", "SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could", "_LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ)", "not v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ -", "logger) p = DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size),", "import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode,", "self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with a", "None: search_root = _firefox_browser_dir() elif _is_path(profile): search_root = profile else:", "is not None: logger.error('safari does not support profiles') if sys.platform", "if big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer", "in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform ==", "pOptionalEntropy: salt? None, # pvReserved: must be NULL None, #", "failed with return code {proc.returncode}. Please consult ' 'the kwallet-query", "None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value,", "comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()):", "logger.warning('failed to decrypt with DPAPI', only_once=True) return None result =", "used if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file", "- KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise NotImplementedError('Must be implemented", "cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key,", "True except ImportError: # although sqlite3 is part of the", "logger self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other':", "manager with a print method. (Optional)\"\"\" # Do not print", "read'): logger.debug('failed to read password from kwallet. Using empty string", "= _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def", "if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform ==", "'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM", "possible to compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544", "nonce = raw_ciphertext[:nonce_length] ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return", "c = self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8') else:", "read password from kwallet. Using empty string instead') # this", "find-generic-password to obtain password from OSX keychain') try: proc =", "'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return", "return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger)", "- https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure): _fields_", "sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform:", "= p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because", "ydl=None): self._ydl = ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message)", "raw_ciphertext[nonce_length:-authentication_tag_length] authentication_tag = raw_ciphertext[-authentication_tag_length:] return _decrypt_aes_gcm(ciphertext, self._v10_key, nonce, authentication_tag, self._logger)", "sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = {", "nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce)", "f'as the `secretstorage` module could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS", "{num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid", "browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User", "= proc.communicate_or_kill() if stdout[-1:] == b'\\n': stdout = stdout[:-1] return", "def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext,", "UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8 decoding failed',", "cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in", "num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes} bytes') def", "= os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome':", "considered 'old data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm", "prefix = b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None", "except KeyError: logger.error('no encrypted key in Local State') return None", "from hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes,", "enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records')", "= _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE:", "proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ],", "elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring =", "be NULL None, # pPromptStruct: information about prompts to display", "False try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE", "== 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption", "_extract_safari_cookies(profile, logger): if profile is not None: logger.error('safari does not", "{SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does not seem", "( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie", "= p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field 3')", "warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def error(self, message):", "cookies from safari') return jar class ParserError(Exception): pass class DataParser:", "'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox')", "None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other':", "flags to determine which keyring backend # it has chosen", "to organise keys in the same way as KWallet, #", "def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if", "a key which is encrypted with DPAPI - not v10:", "Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr", "parts of the database structure is the same - there", "= unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally: if", "elif 'xfce' in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in", "0: logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet =", "MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger password =", "# match 'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service'", "import datetime, timedelta, timezone from enum import Enum, auto from", "'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') #", "file == filename: paths.append(os.path.join(curr_root, file)) return None if not paths", "in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage': return item.get_secret()", "find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root,", "os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases if", "cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie", "_get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'): config =", "cookie because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size, 'space", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session =", "# this may be a bug as the intended behaviour", "key (keyring) and more key derivation iterations than linux -", "keyring, logger) self._v11_key = None if password is None else", "profile is not None and _is_path(profile): profile = os.path.expanduser(profile) return", "from {browser_name} without sqlite3 support. ' 'Please use a python", "here and there which are skipped during parsing \"\"\" if", "is chosen, all cookies are stored as v10 (so no", "{sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie", "not None: output_jar.filename = jar.filename return output_jar def _is_path(value): return", "os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config,", "YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as", "return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session", "does not check hasEntry and instead # just tries to", "jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar,", "search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path", "{i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None,", "0, 'other': 0} @staticmethod def derive_key(password): # values from #", "f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)", "YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True except", "'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'} class YDLLogger: def", "path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor:", "i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset,", "files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files", "return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename, logger):", "cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None", "os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera':", "sys.platform in ('linux', 'linux2'): config = _config_home() browser_dir = {", "tempfile from datetime import datetime, timedelta, timezone from enum import", "only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] +=", "= {'v10': 0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password):", "store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call", "self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key =", "page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\"", "to display 0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if", "a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config", "because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)", "enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0,", "DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets =", "logger.debug(f'a cookies page of size {len(data)} has no cookies') return", "p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER", "while starting chrome. # this may be a bug as", "# Do not print to files/pipes, loggers, or when --no-progress", "== 'darwin': return os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}')", "comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux: - cookies are", "_create_progress_bar(logger) as progress_bar: for i, record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie", "profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if", "browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger):", "find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"')", "- v11: AES-CBC encrypted with an OS protected key (keyring)", "'included in the kwallet package for your distribution') return b''", "self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def derive_key(password):", "- cookies are either v10 or not v10 - v10:", "b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be", "profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile,", "on the activate desktop environment [2] Mac: - cookies are", "if cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform", "SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT =", "{ 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'),", "= f' ({failed_cookies} could not be decrypted)' else: failed_message =", "the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn =", "key which is encrypted with DPAPI - not v10: encrypted", "failed_cookies = 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar:", "stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running find-generic-password:", "raise FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting", "p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError:", "_get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in column_names else", "self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) return None", "failed. Possibly the key is wrong?', only_once=True) return None def", "1 # any other prefix means the data is DPAPI", "_LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name,", "logger): p = DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown", "be stored in various places depending on the activate desktop", "_choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name,", "`secretstorage` module is not installed. ' 'Please install by running", "xdg_current_desktop == 'Unity': if desktop_session is not None and 'gnome-fallback'", "v10 - v10: AES-CBC encrypted with an OS protected key", "Possibly the key is wrong?', only_once=True) return None def _decrypt_aes_gcm(ciphertext,", "with _create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in os.walk(root):", "}[browser_name] else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names", "os.path.expanduser('~/Library/Application Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): #", "'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera'", "# values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16)", "data self.cursor = 0 self._logger = logger def read_bytes(self, num_bytes):", "as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def", "_get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return", "data appears to be out of date but the important", "chosen, all cookies are stored as v10 (so no keyring", "raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None and", "key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar", "{'v10': 0, 'other': 0} @property def cookie_counts(self): return self._cookie_counts def", "False SECRETSTORAGE_UNAVAILABLE_REASON = ( 'as the `secretstorage` module is not", "input') data = self._data[self.cursor:end] self.cursor = end return data def", "domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={})", "it can be observed that chromium lists all keys #", "# pvReserved: must be NULL None, # pPromptStruct: information about", "'Please use a python interpreter compiled with sqlite3 support') return", "table_info] def _find_most_recently_used_file(root, filename, logger): # if there are multiple", ".aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import", "compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path,", "return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet", "= aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to decrypt", "_fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in", "elif not is_encrypted: unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies >", "= env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is", "key (keyring) - v11 keys can be stored in various", "_decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import", "return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc", "Do not print to files/pipes, loggers, or when --no-progress is", "_ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page", "parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar class", "ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None and _is_path(profile):", "- [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self, encrypted_value): raise", "else: self._cookie_counts['other'] += 1 # any other prefix means the", "could not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium',", "@property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value): version =", "_choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop", "elif _is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile)", "finally: if cursor is not None: cursor.connection.close() def _firefox_browser_dir(): if", "iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self, encrypted_value):", "R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera", "self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} @staticmethod def", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return", "self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True) return None", "failed_message = f' ({failed_cookies} could not be decrypted)' else: failed_message", "< 0: raise ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self,", "_create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for", "important parts of the database structure is the same -", "_LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION'", "sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin': return", "= path.decode('utf-8') is_encrypted = not value and encrypted_value if is_encrypted:", "v10: AES-GCM encrypted with a key which is encrypted with", "'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'), 'vivaldi': os.path.join(appdata, 'Vivaldi'), }[browser_name] else:", "elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE':", "file in files: i += 1 progress_bar.print(f'Searching for \"{filename}\": {i:", "if not SQLITE_AVAILABLE: logger.warning('Cannot extract cookies from firefox without sqlite3", "try: proc = Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder',", "filename: paths.append(os.path.join(curr_root, file)) return None if not paths else max(paths,", "keys # and presumably searches for its key in the", "module is not installed. ' 'Please install by running `python3", "'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32': appdata_local =", "stored in various places depending on the activate desktop environment", "\"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as", "logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name", "if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring ==", "_LinuxDesktopEnvironment.OTHER: linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring", "port=None, port_specified=False, domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False,", "DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger):", "return None logger.debug(f'Found local state file at \"{path}\"') with open(path,", "DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer)", "expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value != expected_value:", "else: raise ValueError(f'unsupported platform: {sys.platform}') # Linux keyring names can", "# will not be sufficient in all cases. keyring =", "elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else:", "is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0}", "'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform ==", "loggers, or when --no-progress is used if not self._ydl or", "platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): logger.debug('Trying secondary", ") from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter,", "= proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read NetworkWallet')", "= MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0)", "return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts", "jar finally: if cursor is not None: cursor.connection.close() def _firefox_browser_dir():", "| grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so", "return None def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State',", "'Chromium', 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium',", "_is_path(profile): search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path", "PANTHEON = auto() UNITY = auto() XFCE = auto() class", "(host, name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie", "logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot extract", "# EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce =", "stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running kwallet-query:", "while True: c = self.read_bytes(1) if c == b'\\x00': return", "profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile else: if", "self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:]", "string instead') # this sometimes occurs in KDE because chrome", "compiled with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if", "os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles') search_root =", "{ 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium':", "p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for", "= ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable", "must be NULL None, # pPromptStruct: information about prompts to", "= {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name", "{self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip of {num_bytes}", "cookies are either v10 or not v10 - v10: AES-CBC", "bytes') end = self.cursor + num_bytes if end > len(self._data):", "printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if", "{'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not", "in desktop_session: return _LinuxDesktopEnvironment.XFCE else: if 'GNOME_DESKTOP_SESSION_ID' in env: return", "def _get_windows_v10_key(browser_root, logger): path = _find_most_recently_used_file(browser_root, 'Local State', logger) if", "compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils import", "with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc -", "timedelta, timezone from enum import Enum, auto from hashlib import", "MultilinePrinter(file, preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return", "p.skip_to(record_offsets[0], 'unknown page header field') with _create_progress_bar(logger) as progress_bar: for", "ParserError(f'invalid skip of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset", "decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar", "class ParserError(Exception): pass class DataParser: def __init__(self, data, logger): self._data", "auto from hashlib import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes,", "description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001,", "p.read_uint() p.skip(4, 'unknown record field 1') flags = p.read_uint() is_secure", "Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'),", "host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8')", "return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return", "tmpdir: cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory", "from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp')", "f' ({failed_cookies} could not be decrypted)' else: failed_message = ''", "details') return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to", "error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context", "Possibly the key is wrong?', only_once=True) return None try: return", "installed. ' 'Please install by running `python3 -m pip install", "# although sqlite3 is part of the standard library, it", "# sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE = False try: import", "cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry,", "with open(path, encoding='utf8') as f: data = json.load(f) try: base64_key", "tmpdir): # cannot open sqlite databases if they are already", "os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None,", "GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION', None)", "# pPromptStruct: information about prompts to display 0, # dwFlags", "SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if", "pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from", "else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir,", "return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can", "column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in", "@staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password,", "means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value,", "OSX keychain') try: proc = Popen( ['security', 'find-generic-password', '-w', #", "'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata,", "0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return", "ValueError(f'unsupported browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise", "read from KWallet. kwallet-query should be' 'included in the kwallet", "if sys.platform == 'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform", "if c == b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self,", "if browser_name not in SUPPORTED_BROWSERS: raise ValueError(f'unsupported browser: \"{browser_name}\"') if", "starting chrome. # this may be a bug as the", "None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc,", "FROM cookies') jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies =", "= decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return", "== _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment == _LinuxDesktopEnvironment.OTHER: linux_keyring", "elif xdg_current_desktop == 'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE':", "= Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE,", "Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge':", "bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise ParserError(f'invalid skip", "parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data", "{len(jar)} cookies from safari') return jar class ParserError(Exception): pass class", "else profile else: if config['supports_profiles']: search_root = os.path.join(config['browser_dir'], profile) else:", "are stored as v10 (so no keyring password is required)", "json import os import shutil import struct import subprocess import", "dirs, files in os.walk(root): for file in files: i +=", "{len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies", "Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'),", "keyring password is required) return None assert False, f'Unknown keyring", "output_jar = YoutubeDLCookieJar() for jar in jars: for cookie in", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session = env.get('DESKTOP_SESSION',", "= bool(flags & 0x0001) p.skip(4, 'unknown record field 2') domain_offset", "# Linux keyring names can be determined by snooping on", "value_offset = p.read_uint() p.skip(8, 'unknown record field 3') expiration_date =", "return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment =", "chromium lists all keys # and presumably searches for its", "p.skip_to(record_size, 'space at the end of the record') cookie =", "debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl:", "p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record field", "stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def", "else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome',", "description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')", "_mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp())", "proc = Popen( ['security', 'find-generic-password', '-w', # write password to", "if cookie_database_path is None: raise FileNotFoundError(f'could not find {browser_name} cookies", "return self._cookie_counts def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext =", "'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft Edge'), 'opera': os.path.join(appdata, 'com.operasoftware.Opera'),", "the key is wrong?', only_once=True) return None try: return plaintext.decode('utf-8')", "linux - not v10: 'old data' stored as plaintext Windows:", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger): self._logger", "# when basic text is chosen, all cookies are stored", "= [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies == 0:", "self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once)", "unencrypted_cookies += 1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message =", "True: c = self.read_bytes(1) if c == b'\\x00': return b''.join(buffer).decode('utf-8')", "* 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8')", "= parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari') return jar", "= {'v10': 0, 'other': 0} @staticmethod def derive_key(password): # values", "= data self.cursor = 0 self._logger = logger def read_bytes(self,", "version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is None:", "None and 'gnome-fallback' in desktop_session: return _LinuxDesktopEnvironment.GNOME else: return _LinuxDesktopEnvironment.UNITY", "version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path),", "if they are already in use (e.g. by the browser)", "self._cookie_counts['other'] += 1 # any other prefix means the data", "None logger.debug(f'Found local state file at \"{path}\"') with open(path, encoding='utf8')", "None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie", "= _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0} @property", "Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def", "are already in use (e.g. by the browser) database_copy_path =", "ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret =", "is_encrypted, cookie = _process_chrome_cookie(decryptor, *line) if not cookie: failed_cookies +=", "# if there are multiple browser profiles, take the most", "return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if", "= p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to", "sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie", "encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8')", "b'' # the Gnome keyring does not seem to organise", "value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar = YoutubeDLCookieJar()", "this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *,", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_root, logger):", "'other': 0} @staticmethod def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm", "[row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root, filename, logger): #", "= xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity': if desktop_session is not", "in all cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger)", "browser_keyring_name, logger, *, keyring=None): if sys.platform in ('linux', 'linux2'): return", "> 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes <", "key in the list. It appears that we must do", "f.read() jar = parse_safari_cookies(cookies_data, logger=logger) logger.info(f'Extracted {len(jar)} cookies from safari')", "return data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if", "not support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies',", "Popen([ 'kwallet-query', '--read-password', f'{browser_keyring_name} Safe Storage', '--folder', f'{browser_keyring_name} Keys', network_wallet", "'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif", "return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session in", "elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome", "= p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return", "record field 1') flags = p.read_uint() is_secure = bool(flags &", "the list. It appears that we must do the same.", "= { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config,", "in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value, encrypted_value, path,", "2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint()", "stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed to read", "table = cursor.fetchall() total_cookie_count = len(table) for i, (host, name,", "found. KWallet and kwallet-query ' 'must be installed to read", "os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari cookies", "page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger)", "pass class DataParser: def __init__(self, data, logger): self._data = data", "not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar", "by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if", "cookies from firefox without sqlite3 support. ' 'Please use a", "as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root,", "ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human readable description of", "'Unity': if desktop_session is not None and 'gnome-fallback' in desktop_session:", "man page for details') return b'' else: if stdout.lower().startswith(b'failed to", "os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User", "None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not encrypted_key.startswith(prefix):", "preserve_output=False) printer.print = lambda message: printer.print_at_line(f'[Cookies] {message}', 0) return printer", "'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi':", "ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, # ppszDataDescr: human", "expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar)", "expand_path try: import sqlite3 SQLITE_AVAILABLE = True except ImportError: #", "p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages = p.read_uint(big_endian=True)", "find local state file') return None logger.debug(f'Found local state file", "running find-generic-password: {error_to_str(e)}') return None def _get_windows_v10_key(browser_root, logger): path =", "progress_bar(self): \"\"\"Return a context manager with a print method. (Optional)\"\"\"", "import pbkdf2_hmac from .aes import ( aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, )", "f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError:", "= os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could not find safari", "if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file =", "path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted", "data def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value", "_LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\" OTHER = auto() CINNAMON =", "[1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_linux.cc - KeyStorageLinux::CreateService \"\"\" def decrypt(self,", "backend # it has chosen to use # chromium --enable-logging=stderr", "path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown record field", "v10 or v11 - v10: AES-CBC encrypted with a fixed", "if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager with", "it, but that doesn't matter here. return b'' else: logger.debug('password", "logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key =", "1 jar.set_cookie(cookie) if failed_cookies > 0: failed_message = f' ({failed_cookies}", "BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda message:", "jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *,", "_LinuxDesktopEnvironment.XFCE elif desktop_session is not None: if desktop_session in ('mate',", "'progress_bar'): printer = logger.progress_bar() if printer: return printer printer =", "does not seem to organise keys in the same way", "with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData)", "\"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium':", "profile is None: search_root = config['browser_dir'] elif _is_path(profile): search_root =", "snooping on dbus while opening the browser in KDE: #", "search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if", "if number_of_cookies == 0: logger.debug(f'a cookies page of size {len(data)}", "= name.decode('utf-8') value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted =", "def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot", "profile, keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE:", "value (which kwallet returns \"\") whereas kwallet-query # checks hasEntry.", "= 'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5',", "return stdout except Exception as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}')", "None: if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde'", "search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile", "profile is not None: logger.error('safari does not support profiles') if", "kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE:", "- v10: AES-CBC encrypted with a fixed key - v11:", "{_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS", "profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file", "total_cookie_count = len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie", "v10: 'old data' stored as plaintext Windows: - cookies are", "body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger) for page_size", "keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}')", "the automatic detection # will not be sufficient in all", "data = self._data[self.cursor:end] self.cursor = end return data def expect_bytes(self,", "if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring ==", "= { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata,", "return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None,", "distribution') return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([", "files/pipes, loggers, or when --no-progress is used if not self._ydl", "and there which are skipped during parsing \"\"\" if jar", "in jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename =", "not find safari cookies database') with open(cookies_path, 'rb') as f:", "'space at the end of the record') cookie = compat_cookiejar_Cookie(", "def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext =", "= os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome':", "lambda _: None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars", "read_double(self, big_endian=False): data_format = '>d' if big_endian else '<d' return", "environment: {desktop_environment.name}') if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif", "logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1', password, salt,", "sqlite3 is part of the standard library, it is possible", "= _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of", "_parse_safari_cookies_page(data, jar, logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature')", "pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts def", "R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'),", "cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure):", "\"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}') if desktop_environment", "which does a dbus call to the following function: https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html", "local state file') return None logger.debug(f'Found local state file at", "could not be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)}", "value = decryptor.decrypt(encrypted_value) if value is None: return is_encrypted, None", "\"\"\"Return a context manager with a print method. (Optional)\"\"\" #", "return stdout except Exception as e: logger.warning(f'exception running find-generic-password: {error_to_str(e)}')", "jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data,", "else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except", "logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint()", "MultilinePrinter, QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try:", "nonce_length = 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length", "_extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring,", "_get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif", "the Gnome keyring does not seem to organise keys in", "max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for", "if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi' if sys.platform", "database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return", "'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space", "KWallet and kwallet-query ' 'must be installed to read from", "name, value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i:", "# pDataIn None, # ppszDataDescr: human readable description of pDataIn", "def _decrypt_windows_dpapi(ciphertext, logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes", "raise NotImplementedError('Must be implemented by sub classes') @property def cookie_counts(self):", "tries to read the value (which kwallet returns \"\") whereas", "'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera': os.path.join(appdata_roaming,", "def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>',", "network_wallet except Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}')", "enum import Enum, auto from hashlib import pbkdf2_hmac from .aes", "return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile,", "search_root = os.path.join(config['browser_dir'], profile) else: logger.error(f'{browser_name} does not support profiles')", "return { 'browser_dir': browser_dir, 'keyring_name': keyring_name, 'supports_profiles': browser_name not in", "# pOptionalEntropy: salt? None, # pvReserved: must be NULL None,", "self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0} @staticmethod", "page for details') return b'' else: if stdout.lower().startswith(b'failed to read'):", "run with the following flags to determine which keyring backend", "self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data), description) def", "LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger)", "prefix means the data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return", "iterations, key_length): return pbkdf2_hmac('sha1', password, salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext,", "open(cookies_path, 'rb') as f: cookies_data = f.read() jar = parse_safari_cookies(cookies_data,", "return jar class ParserError(Exception): pass class DataParser: def __init__(self, data,", "the database structure is the same - there are a", "command not found. KWallet and kwallet-query ' 'must be installed", "else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The", "None: self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True) return", "in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return", "be decrypted)' else: failed_message = '' logger.info(f'Extracted {len(jar)} cookies from", "base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local", "stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0:", "blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None,", "from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor = None try:", "return b'' network_wallet = _get_kwallet_network_wallet(logger) try: proc = Popen([ 'kwallet-query',", "is None: logger.error('kwallet-query command not found. KWallet and kwallet-query '", "len(table) for i, line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count:", "return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name", "2>&1 | grep key_storage_ # Chromium supports a flag: --password-store=<basic|gnome|kwallet>", "# https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length = 96 // 8 #", "b'DPAPI' if not encrypted_key.startswith(prefix): logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):],", "stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if stdout[-1:] == b'\\n':", "'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root,", "{sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if sys.platform in ('linux', 'linux2'):", "record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc -", "os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config,", "= 96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length =", "record field 2') domain_offset = p.read_uint() name_offset = p.read_uint() path_offset", "found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other']", "in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum):", "= expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True)", "whereas kwallet-query # checks hasEntry. To verify this: # dbus-monitor", "self._v10_key = None if password is None else self.derive_key(password) self._cookie_counts", "else: logger.error(f'{browser_name} does not support profiles') search_root = config['browser_dir'] cookie_database_path", "_decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other'] += 1 return None class", "to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus", "KDE = auto() PANTHEON = auto() UNITY = auto() XFCE", "value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry,", "== _LinuxKeyring.BASICTEXT: # when basic text is chosen, all cookies", "opening the browser in KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name", "cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def _find_most_recently_used_file(root,", "_is_path(value): return os.path.sep in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if", "config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir']", "e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name,", "decrypt v10 cookies: no key found', only_once=True) return None return", "except Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return", "a context manager with a print method. (Optional)\"\"\" # Do", "initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try:", "logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring", "profiles, take the most recently used one i, paths =", "1 if self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no", "key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' * 16): plaintext", "'Cookies', logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find", "import json import os import shutil import struct import subprocess", "except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding", "UTF-8 decoding failed. Possibly the key is wrong?', only_once=True) return", "= _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config,", "be a bug as the intended behaviour is to generate", "password from OSX keychain') try: proc = Popen( ['security', 'find-generic-password',", "== 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave':", "dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this may", "message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return a context manager", "> len(self._data): raise ParserError('reached end of input') data = self._data[self.cursor:end]", "def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message,", "os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config,", "path.decode('utf-8') is_encrypted = not value and encrypted_value if is_encrypted: value", "all cases. keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen", "path = path.decode('utf-8') is_encrypted = not value and encrypted_value if", "raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from", "logger.error('failed to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring,", "= _get_column_names(cursor, 'cookies') secure_column = 'is_secure' if 'is_secure' in column_names", "with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con) for item in", "return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True:", "as v10 (so no keyring password is required) return None", "\"type=method_return\" # while starting chrome. # this may be a", "return item.get_secret() else: logger.error('failed to read from keyring') return b''", "v10 or not v10 - v10: AES-GCM encrypted with a", "failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies += 1", "= p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8, 'unknown", "to read from KWallet. kwallet-query should be' 'included in the", "# match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if", "the MAC check failed. Possibly the key is wrong?', only_once=True)", "6d}/{total_cookie_count: 6d}') cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False,", "profile) cookie_database_path = _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None:", "None, # ppszDataDescr: human readable description of pDataIn None, #", "decrypt cookie (AES-GCM) because the MAC check failed. Possibly the", "to determine which keyring backend # it has chosen to", "ctypes.byref(blob_out) # pDataOut ) if not ret: logger.warning('failed to decrypt", "'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium', 'vivaldi': 'Vivaldi'", "linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the wallet used", "logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return", "install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON", "same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col = secretstorage.get_default_collection(con)", "cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is not None: cookie_file", "rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data, jar=None, logger=YDLLogger()): \"\"\" References:", "def expect_bytes(self, expected_value, message): value = self.read_bytes(len(expected_value)) if value !=", "shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def _get_column_names(cursor, table_name):", "blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def", "when --no-progress is used if not self._ydl or self._ydl.params.get('noprogress') or", "'Chromium', 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome', }[browser_name]", "None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 #", "elif sys.platform == 'darwin': appdata = os.path.expanduser('~/Library/Application Support') browser_dir =", "ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))", "Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the", "ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self, message):", "{'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS |", "# boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext", "= cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in table_info] def", "as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value class WindowsChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self,", "0: failed_message = f' ({failed_cookies} could not be decrypted)' else:", "boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce", "# chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ # Chromium", "path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars): output_jar = YoutubeDLCookieJar() for jar in", "None return printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = []", "timezone from enum import Enum, auto from hashlib import pbkdf2_hmac", "is encrypted with DPAPI - not v10: encrypted with DPAPI", "= 0 unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table", "'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if not", "if not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies')", "stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if proc.returncode != 0: logger.warning('failed", "XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET", "elif keyring == _LinuxKeyring.BASICTEXT: # when basic text is chosen,", "3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841", "secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def", "else: return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif", "= YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count", "structure is the same - there are a few bytes", "tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger)", "skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes", "return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name", "is None: raise FileNotFoundError(f'could not find {browser_name} cookies database in", "expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return record_size def parse_safari_cookies(data,", "_get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0} @property def", "(e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path)", "if version == b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key,", "0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer =", "auto() UNITY = auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\"", "to generate a random password and store # it, but", "def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases if they", "# it has chosen to use # chromium --enable-logging=stderr --v=1", "take the most recently used one i, paths = 0,", "'chrome': os.path.join(config, 'google-chrome'), 'chromium': os.path.join(config, 'chromium'), 'edge': os.path.join(config, 'microsoft-edge'), 'opera':", "keyring_name, 'supports_profiles': browser_name not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile,", "generate a random password and store # it, but that", "0, 'v11': 0, 'other': 0} @staticmethod def derive_key(password): # values", "def skip(self, num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes}", "os.path.expanduser('~/Library/Application Support') browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata,", "install by running `python3 -m pip install secretstorage`.') except Exception", "def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}')", "unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector)) try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to", "`python3 -m pip install secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE", "class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger =", "try: import secretstorage SECRETSTORAGE_AVAILABLE = True except ImportError: SECRETSTORAGE_AVAILABLE =", "else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout = stdout[:-1]", "is None: logger.error('could not find local state file') return None", "xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif desktop_session is not None:", "num_bytes if end > len(self._data): raise ParserError('reached end of input')", "that we must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init())", "host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies') jar", "OS protected key (keyring) and more key derivation iterations than", "aes_cbc_decrypt_bytes, aes_gcm_decrypt_and_verify_bytes, unpad_pkcs7, ) from .compat import compat_b64decode, compat_cookiejar_Cookie from", "be run with the following flags to determine which keyring", "logger) self._v11_key = None if password is None else self.derive_key(password)", "nonce) except ValueError: logger.warning('failed to decrypt cookie (AES-GCM) because the", "interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if profile is", "here. return b'' else: logger.debug('password found') if stdout[-1:] == b'\\n':", "desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session:", "cookie_database_path is None: raise FileNotFoundError(f'could not find firefox cookies database", "encoding='utf8') as f: data = json.load(f) try: base64_key = data['os_crypt']['encrypted_key']", "p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value", "_ in range(number_of_pages)] return page_sizes, p.cursor def _parse_safari_cookies_page(data, jar, logger):", "that chromium lists all keys # and presumably searches for", "YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p = DataParser(data[body_start:], logger)", "few bytes here and there which are skipped during parsing", "try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-CBC)", "= ydl def debug(self, message): if self._ydl: self._ydl.write_debug(message) def info(self,", "\"\") whereas kwallet-query # checks hasEntry. To verify this: #", "curr_root, dirs, files in os.walk(root): for file in files: i", "jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not", "cookie in jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename", "import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter from .utils", "num_bytes, description='unknown'): if num_bytes > 0: self._logger.debug(f'skipping {num_bytes} bytes ({description}):", "authentication_tag_length = 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext", "cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise FileNotFoundError('could", "sys.platform == 'darwin' else 'Chrome', }[browser_name] browsers_without_profiles = {'opera'} return", "in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'],", "kwallet-query man page for details') return b'' else: if stdout.lower().startswith(b'failed", "--password-store=<basic|gnome|kwallet> so the automatic detection # will not be sufficient", "cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies') jar", "return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key),", "moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table =", "jar = YoutubeDLCookieJar() failed_cookies = 0 unencrypted_cookies = 0 with", "def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note: chrome/chromium can be run", "with an OS protected key (keyring) and more key derivation", "_get_linux_desktop_environment(env): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc GetDesktopEnvironment \"\"\" xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None) desktop_session", "use # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_ #", "p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger): p =", "__init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key =", "(Optional)\"\"\" # Do not print to files/pipes, loggers, or when", "printer = QuietMultilinePrinter() printer.print = lambda _: None return printer", "'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'}", "elif sys.platform == 'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%')", "= 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length] ciphertext =", "logger.info(f'Extracted {len(jar)} cookies from firefox') return jar finally: if cursor", "= DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record field", "xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop == 'X-Cinnamon': return", "== 'Unity': if desktop_session is not None and 'gnome-fallback' in", "\"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium',", "proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with return code", "except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print = lambda", "('pbData', ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out", "Please consult ' 'the kwallet-query man page for details') return", "if version == b'v10': self._cookie_counts['v10'] += 1 if self._v10_key is", "'-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout,", "if big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False):", "State', logger) if path is None: logger.error('could not find local", "import DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))]", "if not paths else max(paths, key=lambda path: os.lstat(path).st_mtime) def _merge_cookie_jars(jars):", "logger) if path is None: logger.error('could not find local state", "in jars: for cookie in jar: output_jar.set_cookie(cookie) if jar.filename is", "_config_home(): return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open", "def decrypt(self, encrypted_value): version = encrypted_value[:3] ciphertext = encrypted_value[3:] if", "one i, paths = 0, [] with _create_progress_bar(logger) as progress_bar:", "try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names =", "if jar.filename is not None: output_jar.filename = jar.filename return output_jar", "path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) return", "domain_offset = p.read_uint() name_offset = p.read_uint() path_offset = p.read_uint() value_offset", "ctypes.POINTER(ctypes.c_char))] buffer = ctypes.create_string_buffer(ciphertext) blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out =", "YDLLogger: def __init__(self, ydl=None): self._ydl = ydl def debug(self, message):", "def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected", "return b'' else: if stdout.lower().startswith(b'failed to read'): logger.debug('failed to read", "= DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData( ctypes.byref(blob_in), # pDataIn None, #", "AES-CBC encrypted with an OS protected key (keyring) and more", "{i: 6d} files searched') if file == filename: paths.append(os.path.join(curr_root, file))", "key is wrong?', only_once=True) return None try: return plaintext.decode('utf-8') except", "!= 0: logger.warning('failed to read NetworkWallet') return default_wallet else: network_wallet", "os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) def _open_database_copy(database_path, tmpdir): # cannot open sqlite databases", "{error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage", "host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8')", "logger): \"\"\" References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD", "os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor() def", "from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): # note:", "browser: \"{browser_name}\"') if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported", "logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key", "if desktop_environment == _LinuxDesktopEnvironment.KDE: linux_keyring = _LinuxKeyring.KWALLET elif desktop_environment ==", "classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None): if sys.platform in", "= data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted key in Local State')", "browser_specification is not None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name,", "= p.read_cstring() p.skip_to(name_offset) name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring()", "flag: --password-store=<basic|gnome|kwallet> so the automatic detection # will not be", "from enum import Enum, auto from hashlib import pbkdf2_hmac from", "as progress_bar: for curr_root, dirs, files in os.walk(root): for file", "the standard library, it is possible to compile python without", "cookies page of size {len(data)} has no cookies') return p.skip_to(record_offsets[0],", "= len(table) for i, (host, name, value, path, expiry, is_secure)", "struct import subprocess import sys import tempfile from datetime import", "return _LinuxDesktopEnvironment.GNOME elif 'KDE_FULL_SESSION' in env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER", "def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif", "not SQLITE_AVAILABLE: logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support.", "logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password", "read NetworkWallet') return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet =", "during startup, it can be observed that chromium lists all", "browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(config, 'google-chrome'), 'chromium':", "return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt, iterations, key_length): return pbkdf2_hmac('sha1',", "v10: encrypted with DPAPI Sources: - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/ - [2]", "return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\"", "jar: output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename = jar.filename", "Data'), 'opera': os.path.join(appdata_roaming, R'Opera Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'),", "from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def", "def __init__(self, data, logger): self._data = data self.cursor = 0", "== 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE", "96 // 8 # boringssl # EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16", "# Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection", "cookie = compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False, domain=domain, domain_specified=bool(domain),", "logger): p = DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies =", "method. (Optional)\"\"\" # Do not print to files/pipes, loggers, or", "'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop == 'XFCE': return _LinuxDesktopEnvironment.XFCE elif", "1 progress_bar.print(f'Searching for \"{filename}\": {i: 6d} files searched') if file", "Exception as e: logger.warning(f'exception while obtaining NetworkWallet: {e}') return default_wallet", "has no cookies') return p.skip_to(record_offsets[0], 'unknown page header field') with", "= self._ydl._out_files['error'] try: if not file.isatty(): return except BaseException: return", "p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except", "auto() KDE = auto() PANTHEON = auto() UNITY = auto()", "'/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if", "to files/pipes, loggers, or when --no-progress is used if not", "_extract_firefox_cookies(profile, logger) elif browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif", "== b'v10': self._cookie_counts['v10'] += 1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif", "_LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment", "= stdout[:-1] return stdout except Exception as e: logger.warning(f'exception running", "name = p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value =", "DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return", "self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True: c =", "self._v10_key = _get_windows_v10_key(browser_root, logger) self._cookie_counts = {'v10': 0, 'other': 0}", "should be' 'included in the kwallet package for your distribution')", "'linux2'): config = _config_home() browser_dir = { 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'),", "appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'),", "_get_chromium_based_browser_settings(browser_name) if profile is None: search_root = config['browser_dir'] elif _is_path(profile):", "logger) p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger):", "plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce) except ValueError: logger.warning('failed to", "{len(jar)} cookies from firefox') return jar finally: if cursor is", "_get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if password is None else", "if is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None: return", "seem to organise keys in the same way as KWallet,", "if cookie_file is not None: cookie_file = expand_path(cookie_file) jar =", "if jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start =", "browser_name == 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS:", "port=None, port_specified=False, domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False,", "FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger) as progress_bar: table", "config['browser_dir'] elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if", "big_endian else '<d' return struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer =", "description='unknown'): self.skip_to(len(self._data), description) def _mac_absolute_time_to_posix(timestamp): return int((datetime(2001, 1, 1, 0,", "domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None, rest={}) jar.set_cookie(cookie)", "result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def _config_home(): return", "progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i, line", "1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p", "not cookie: failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies", "observed that chromium lists all keys # and presumably searches", "datetime import datetime, timedelta, timezone from enum import Enum, auto", "must do the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con:", "p.read_uint() p.skip(8, 'unknown record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date", "Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True", "p.read_bytes(record_length) p.skip_to_end('space in between pages') def _parse_safari_cookies_record(data, jar, logger): p", "key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else:", "the same way as KWallet, # using `dbus-monitor` during startup,", "the same. # https://github.com/jaraco/keyring/issues/556 with contextlib.closing(secretstorage.dbus_init()) as con: col =", "unencrypted_cookies = 0 with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall()", "logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly", "its key in the list. It appears that we must", "record field 3') expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) #", "with open(cookies_path, 'rb') as f: cookies_data = f.read() jar =", "logger) else: raise NotImplementedError(f'Chrome cookie decryption is not supported on", "'database signature') number_of_pages = p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _", "comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return jar", "{len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown page header field')", "try: proc = Popen( ['security', 'find-generic-password', '-w', # write password", "not find local state file') return None logger.debug(f'Found local state", "if profile is not None and _is_path(profile): profile = os.path.expanduser(profile)", "None: raise FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"')", "in KDE because chrome does not check hasEntry and instead", "has chosen to use # chromium --enable-logging=stderr --v=1 2>&1 |", "secretstorage`.') except Exception as _err: SECRETSTORAGE_AVAILABLE = False SECRETSTORAGE_UNAVAILABLE_REASON =", "cookies are stored as v10 (so no keyring password is", "is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value = value.decode('utf-8')", "!= expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def", "implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None):", "+= 1 # other prefixes are considered 'old data' which", "'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif", "{keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to obtain password from", "read_cstring(self): buffer = [] while True: c = self.read_bytes(1) if", "output_jar.set_cookie(cookie) if jar.filename is not None: output_jar.filename = jar.filename return", "os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User", "*, keyring=None): if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger,", "env: return _LinuxDesktopEnvironment.KDE return _LinuxDesktopEnvironment.OTHER def _choose_linux_keyring(logger): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend", "= json.load(f) try: base64_key = data['os_crypt']['encrypted_key'] except KeyError: logger.error('no encrypted", "= lambda _: None return printer def load_cookies(cookie_file, browser_specification, ydl):", "profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path", "cookies: no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key,", "salt=b'<PASSWORD>', iterations=1003, key_length=16) @property def cookie_counts(self): return self._cookie_counts def decrypt(self,", "keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger):", "use (e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path,", "Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)", "= p.read_uint() p.skip(4, 'unknown record field 1') flags = p.read_uint()", "{sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger", "env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip()", "extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if browser_name == 'firefox': return", "(keyring) - v11 keys can be stored in various places", "info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False):", "if xdg_current_desktop == 'Unity': if desktop_session is not None and", "def _parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature')", "for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer') return jar", "= auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys() def _get_linux_desktop_environment(env):", "salt, iterations, key_length) def _decrypt_aes_cbc(ciphertext, key, logger, initialization_vector=b' ' *", "domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False, comment=None, comment_url=None,", "if desktop_session in ('mate', 'gnome'): return _LinuxDesktopEnvironment.GNOME elif 'kde' in", "if keyring not in (None, *SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"')", "return _LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop", "return printer printer = QuietMultilinePrinter() printer.print = lambda _: None", "'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is", "None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger): self._logger = logger", "CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser:", "name, value, path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar()", "are considered 'old data' which were stored as plaintext #", "prefixes are considered 'old data' which were stored as plaintext", "is None: search_root = config['browser_dir'] elif _is_path(profile): search_root = profile", "0: logger.debug(f'a cookies page of size {len(data)} has no cookies')", "keyring else _choose_linux_keyring(logger) logger.debug(f'Chosen keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET:", "by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented", "__init__(self, browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name, logger)", "derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1,", "os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif", "b'\\n': stdout = stdout[:-1] return stdout except Exception as e:", "'find-generic-password', '-w', # write password to stdout '-a', browser_keyring_name, #", "= _find_most_recently_used_file(search_root, 'cookies.sqlite', logger) if cookie_database_path is None: raise FileNotFoundError(f'could", "return WindowsChromeCookieDecryptor(browser_root, logger) else: raise NotImplementedError(f'Chrome cookie decryption is not", "sub classes') @property def cookie_counts(self): raise NotImplementedError('Must be implemented by", "found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v11_key, self._logger) else: self._cookie_counts['other']", "f'{browser_keyring_name} Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill()", "matter here. return b'' else: logger.debug('password found') if stdout[-1:] ==", "if end > len(self._data): raise ParserError('reached end of input') data", "return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other", "return None try: return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt", "name, value, encrypted_value, path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name", "page header field') with _create_progress_bar(logger) as progress_bar: for i, record_offset", "'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout,", "ParserError(Exception): pass class DataParser: def __init__(self, data, logger): self._data =", "cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is", "= False SECRETSTORAGE_UNAVAILABLE_REASON = f'as the `secretstorage` module could not", "browser_dir = { 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium':", "domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False, comment=None, comment_url=None,", "\"\"\" KWALLET = auto() GNOMEKEYRING = auto() BASICTEXT = auto()", "F841 try: p.skip_to(domain_offset) domain = p.read_cstring() p.skip_to(name_offset) name = p.read_cstring()", "= _find_most_recently_used_file(browser_root, 'Local State', logger) if path is None: logger.error('could", "print to files/pipes, loggers, or when --no-progress is used if", "logger.error('invalid key') return None return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger) def pbkdf2_sha1(password, salt,", "information about prompts to display 0, # dwFlags ctypes.byref(blob_out) #", "[p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a", "domain_initial_dot=host_key.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class", "= p.read_cstring() p.skip_to(path_offset) path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring()", "stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe Storage'],", "0, # dwFlags ctypes.byref(blob_out) # pDataOut ) if not ret:", "- not v10: 'old data' stored as plaintext Windows: -", "== b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'):", "import os import shutil import struct import subprocess import sys", "during parsing \"\"\" if jar is None: jar = YoutubeDLCookieJar()", "files in os.walk(root): for file in files: i += 1", "== 'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return", "xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop ==", "in os.walk(root): for file in files: i += 1 progress_bar.print(f'Searching", "# dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave', 'chrome':", "6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar,", "print method. (Optional)\"\"\" # Do not print to files/pipes, loggers,", "\"\"\" The name of the wallet used to store network", "AES-CBC encrypted with a fixed key - v11: AES-CBC encrypted", "platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger, *, keyring=None):", "to use # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_", "\"{path}\"') with open(path, encoding='utf8') as f: data = json.load(f) try:", "checks hasEntry. To verify this: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" #", "{message}') def warning(self, message, only_once=False): if self._ydl: self._ydl.report_warning(message, only_once) def", "local state file at \"{path}\"') with open(path, encoding='utf8') as f:", "p.read_uint() record_offsets = [p.read_uint() for _ in range(number_of_cookies)] if number_of_cookies", "encrypted with a fixed key - v11: AES-CBC encrypted with", "return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop", "value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed to parse Safari cookie", "NotImplementedError('Must be implemented by sub classes') def get_cookie_decryptor(browser_root, browser_keyring_name, logger,", "with _create_progress_bar(logger) as progress_bar: table = cursor.fetchall() total_cookie_count = len(table)", "not be initialized. {_err}' CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge',", "extract cookies from {browser_name} without sqlite3 support. ' 'Please use", "if value is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie(", "Safari cookie because UTF-8 decoding failed', only_once=True) return record_size p.skip_to(record_size,", "'BraveSoftware/Brave-Browser'), 'chrome': os.path.join(appdata, 'Google/Chrome'), 'chromium': os.path.join(appdata, 'Chromium'), 'edge': os.path.join(appdata, 'Microsoft", "None: browser_name, profile, keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring))", "returns \"\") whereas kwallet-query # checks hasEntry. To verify this:", "else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md if", "secure_column = 'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT", "not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the", "with sqlite3 support') return YoutubeDLCookieJar() if profile is None: search_root", "= 'is_secure' if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key,", "= f'as the `secretstorage` module could not be initialized. {_err}'", "None: cursor.connection.close() def _firefox_browser_dir(): if sys.platform in ('linux', 'linux2'): return", "'X-Cinnamon': return _LinuxDesktopEnvironment.CINNAMON elif xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif", "from firefox') return jar finally: if cursor is not None:", "= [] while True: c = self.read_bytes(1) if c ==", "logger): # if there are multiple browser profiles, take the", "running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not", "return None result = ctypes.string_at(blob_out.pbData, blob_out.cbData) ctypes.windll.kernel32.LocalFree(blob_out.pbData) return result def", "cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is None: raise", "else self.derive_key(password) self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def", "if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return printer", "interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name)", "NetworkWallet: {e}') return default_wallet def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to", "read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger): #", "return b'' # the Gnome keyring does not seem to", "_extract_chrome_cookies(browser_name, profile, keyring, logger) else: raise ValueError(f'unknown browser: {browser_name}') def", "table_name): table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall() return [row[1].decode('utf-8') for row in", "None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value,", "_get_linux_keyring_password(browser_keyring_name, keyring, logger) self._v11_key = None if password is None", "'--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5', 'org.kde.KWallet.networkWallet' ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr =", "is None: raise FileNotFoundError(f'could not find firefox cookies database in", "+= 1 if self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies:", "= logger password = _get_mac_keyring_password(browser_keyring_name, logger) self._v10_key = None if", "_LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.BASICTEXT: # when", "self._v10_key is None: self._logger.warning('cannot decrypt v10 cookies: no key found',", "path, expires_utc, is_secure): host_key = host_key.decode('utf-8') name = name.decode('utf-8') value", "Support/Firefox') else: raise ValueError(f'unsupported platform: {sys.platform}') def _get_chromium_based_browser_settings(browser_name): # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md", "range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies page of size", "decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key", "{sys.platform}') # Linux keyring names can be determined by snooping", "def _get_kwallet_password(browser_keyring_name, logger): logger.debug('using kwallet-query to obtain password from kwallet')", "self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}') elif num_bytes < 0: raise", "if 'is_secure' in column_names else 'secure' cursor.execute(f'SELECT host_key, name, value,", "os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name] elif sys.platform == 'win32':", "can be determined by snooping on dbus while opening the", "the intended behaviour is to generate a random password and", "p.read_uint(big_endian=True) page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)] return page_sizes,", "'edge': os.path.join(config, 'microsoft-edge'), 'opera': os.path.join(config, 'opera'), 'vivaldi': os.path.join(config, 'vivaldi'), }[browser_name]", "{'v10': 0, 'other': 0} @staticmethod def derive_key(password): # values from", "= True except ImportError: # although sqlite3 is part of", "self._cookie_counts['v10'] += 1 if self._v10_key is None: self._logger.warning('cannot decrypt v10", "compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE =", "!= 'darwin': raise ValueError(f'unsupported platform: {sys.platform}') cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies') if", "field 1') flags = p.read_uint() is_secure = bool(flags & 0x0001)", "None: logger.error('safari does not support profiles') if sys.platform != 'darwin':", "finally: if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key,", "sys.platform in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32':", "None) desktop_session = env.get('DESKTOP_SESSION', None) if xdg_current_desktop is not None:", "('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles')", "= config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger) if cookie_database_path is", "elif _is_path(profile): search_root = profile config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles']", "version=0, name=name, value=value, port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path),", "def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification is", "= YoutubeDLCookieJar() for jar in jars: for cookie in jar:", "is None else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0,", "self._v11_key is None: self._logger.warning('cannot decrypt v11 cookies: no key found',", "return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1, key_length=16) @property def cookie_counts(self): return self._cookie_counts", "with a print method. (Optional)\"\"\" # Do not print to", "to stdout '-a', browser_keyring_name, # match 'account' '-s', f'{browser_keyring_name} Safe", "available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b'' # the Gnome keyring does not", "def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure): host_key", "will not be sufficient in all cases. keyring = _LinuxKeyring[keyring]", "'kde' in desktop_session: return _LinuxDesktopEnvironment.KDE elif 'xfce' in desktop_session: return", "return default_wallet else: network_wallet = stdout.decode('utf-8').strip() logger.debug(f'NetworkWallet = \"{network_wallet}\"') return", "jar.filename return output_jar def _is_path(value): return os.path.sep in value def", "from .compat import compat_b64decode, compat_cookiejar_Cookie from .minicurses import MultilinePrinter, QuietMultilinePrinter", "b'' else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout =", "None: raise FileNotFoundError(f'could not find firefox cookies database in {search_root}')", "keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING:", "KDE: # dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" keyring_name = { 'brave': 'Brave',", "_parse_safari_cookies_header(data, logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages", "self._logger = logger def read_bytes(self, num_bytes): if num_bytes < 0:", "is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name, value=value, port=None, port_specified=False,", "= '' logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy()", "- v11 keys can be stored in various places depending", "\"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING = auto()", "is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if xdg_current_desktop == 'Unity':", "printer def load_cookies(cookie_file, browser_specification, ydl): cookie_jars = [] if browser_specification", "data' which were stored as plaintext # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return encrypted_value", "just tries to read the value (which kwallet returns \"\")", "to read from keyring') return b'' def _get_linux_keyring_password(browser_keyring_name, keyring, logger):", "for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe Storage':", "key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc # kNonceLength nonce_length", "cookie_file is not None: cookie_file = expand_path(cookie_file) jar = YoutubeDLCookieJar(cookie_file)", "logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not available {SECRETSTORAGE_UNAVAILABLE_REASON}') return b''", "self._ydl: self._ydl.write_debug(message) def info(self, message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def", "only_once=True) return None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try:", "logger) if cookie_database_path is None: raise FileNotFoundError(f'could not find firefox", "from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query command not found.", "encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if", "== _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring == _LinuxKeyring.GNOMEKEYRING: return", "_LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto() GNOMEKEYRING =", "def __init__(self, browser_keyring_name, logger): self._logger = logger password = _get_mac_keyring_password(browser_keyring_name,", "= logger def read_bytes(self, num_bytes): if num_bytes < 0: raise", "page of size {len(data)} has no cookies') return p.skip_to(record_offsets[0], 'unknown", "empty string instead') # this sometimes occurs in KDE because", "but the important parts of the database structure is the", "if cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name,", "contextlib import ctypes import json import os import shutil import", "progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie = _process_chrome_cookie(decryptor, *line)", "}[browser_name] browsers_without_profiles = {'opera'} return { 'browser_dir': browser_dir, 'keyring_name': keyring_name,", "the same - there are a few bytes here and", "as progress_bar: table = cursor.fetchall() total_cookie_count = len(table) for i,", "== f'{browser_keyring_name} Safe Storage': return item.get_secret() else: logger.error('failed to read", "file.isatty(): return except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print", "= { 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft", "by snooping on dbus while opening the browser in KDE:", "{value} != {expected_value} ({message})') def read_uint(self, big_endian=False): data_format = '>I'", "between pages') def _parse_safari_cookies_record(data, jar, logger): p = DataParser(data, logger)", "printer.print_at_line(f'[Cookies] {message}', 0) return printer def _create_progress_bar(logger): if hasattr(logger, 'progress_bar'):", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def _extract_safari_cookies(profile, logger): if profile is", "expiration_date = _mac_absolute_time_to_posix(p.read_double()) _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841 try:", "in use (e.g. by the browser) database_copy_path = os.path.join(tmpdir, 'temporary.sqlite')", "+= 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self, browser_keyring_name, logger):", "secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name} Safe", "state file at \"{path}\"') with open(path, encoding='utf8') as f: data", "comment=None, comment_url=None, rest={}) jar.set_cookie(cookie) logger.info(f'Extracted {len(jar)} cookies from firefox') return", "be implemented by sub classes') @property def cookie_counts(self): raise NotImplementedError('Must", "Keys', network_wallet ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr = proc.communicate_or_kill() if", "bug as the intended behaviour is to generate a random", "derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_mac.mm return pbkdf2_sha1(password, salt=b'<PASSWORD>', iterations=1003,", "stored as v10 (so no keyring password is required) return", "a print method. (Optional)\"\"\" # Do not print to files/pipes,", "is_secure = bool(flags & 0x0001) p.skip(4, 'unknown record field 2')", "1') flags = p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4,", "return record_size p.skip_to(record_size, 'space at the end of the record')", "as e: logger.warning(f'exception running kwallet-query: {error_to_str(e)}') return b'' def _get_gnome_keyring_password(browser_keyring_name,", "be out of date but the important parts of the", "None) if xdg_current_desktop is not None: xdg_current_desktop = xdg_current_desktop.split(':')[0].strip() if", "= auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET =", "elif keyring == _LinuxKeyring.GNOMEKEYRING: return _get_gnome_keyring_password(browser_keyring_name, logger) elif keyring ==", "may be a bug as the intended behaviour is to", "' 'the kwallet-query man page for details') return b'' else:", "record_offset in enumerate(record_offsets): progress_bar.print(f'Loading cookie {i: 6d}/{number_of_cookies: 6d}') p.skip_to(record_offset, 'space", "instead # just tries to read the value (which kwallet", "[] while True: c = self.read_bytes(1) if c == b'\\x00':", "\"\"\" if jar is None: jar = YoutubeDLCookieJar() page_sizes, body_start", "browser_specification, ydl): cookie_jars = [] if browser_specification is not None:", "= ( 'as the `secretstorage` module is not installed. '", "to compile python without # sqlite support. See: https://github.com/yt-dlp/yt-dlp/issues/544 SQLITE_AVAILABLE", "message): if self._ydl: self._ydl.to_screen(f'[Cookies] {message}') def warning(self, message, only_once=False): if", "elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform == 'darwin':", "or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not file.isatty():", "len(self._data): raise ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor", "signature') number_of_cookies = p.read_uint() record_offsets = [p.read_uint() for _ in", "the important parts of the database structure is the same", "keyring=keyring) elif sys.platform == 'darwin': return MacChromeCookieDecryptor(browser_keyring_name, logger) elif sys.platform", "import shutil import struct import subprocess import sys import tempfile", "return b'' def _get_gnome_keyring_password(browser_keyring_name, logger): if not SECRETSTORAGE_AVAILABLE: logger.error(f'secretstorage not", "= secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label() == f'{browser_keyring_name}", "keyring = _parse_browser_specification(*browser_specification) cookie_jars.append(extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring)) if cookie_file is", "DWORD class DATA_BLOB(ctypes.Structure): _fields_ = [('cbData', DWORD), ('pbData', ctypes.POINTER(ctypes.c_char))] buffer", "'account' '-s', f'{browser_keyring_name} Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)", "\"{keyring}\"') if profile is not None and _is_path(profile): profile =", "of the wallet used to store network passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet", "FileNotFoundError(f'could not find {browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies", "' 'Please use a python interpreter compiled with sqlite3 support')", "search_root = profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path =", "message): value = self.read_bytes(len(expected_value)) if value != expected_value: raise ParserError(f'unexpected", "path, expiry, isSecure FROM moz_cookies') jar = YoutubeDLCookieJar() with _create_progress_bar(logger)", "expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview: Linux:", "YoutubeDLCookieJar(cookie_file) if os.access(cookie_file, os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def", "found') if stdout[-1:] == b'\\n': stdout = stdout[:-1] return stdout", "of {num_bytes} bytes') def skip_to(self, offset, description='unknown'): self.skip(offset - self.cursor,", "b'\\x00': return b''.join(buffer).decode('utf-8') else: buffer.append(c) def skip(self, num_bytes, description='unknown'): if", "error_to_str, expand_path try: import sqlite3 SQLITE_AVAILABLE = True except ImportError:", "= profile else: search_root = os.path.join(_firefox_browser_dir(), profile) cookie_database_path = _find_most_recently_used_file(search_root,", "default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal',", "return None encrypted_key = compat_b64decode(base64_key) prefix = b'DPAPI' if not", "Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local, R'Microsoft\\Edge\\User Data'), 'opera':", "jar, logger): p = DataParser(data, logger) record_size = p.read_uint() p.skip(4,", "recently used one i, paths = 0, [] with _create_progress_bar(logger)", "no keyring password is required) return None assert False, f'Unknown", "logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] =", "\"\"\" default_wallet = 'kdewallet' try: proc = Popen([ 'dbus-send', '--session',", "DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger) p.skip_to_end('footer')", "already in use (e.g. by the browser) database_copy_path = os.path.join(tmpdir,", "records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in between", "as KWallet, # using `dbus-monitor` during startup, it can be", "key, logger, initialization_vector=b' ' * 16): plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key,", "read the value (which kwallet returns \"\") whereas kwallet-query #", "< 0: raise ParserError(f'invalid read of {num_bytes} bytes') end =", "[] if browser_specification is not None: browser_name, profile, keyring =", "logger) else: raise ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting", "return plaintext.decode('utf-8') except UnicodeDecodeError: logger.warning('failed to decrypt cookie (AES-GCM) because", "get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor =", "jar = YoutubeDLCookieJar() page_sizes, body_start = _parse_safari_cookies_header(data, logger) p =", "a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar() if", "{ 'brave': 'Brave', 'chrome': 'Chrome', 'chromium': 'Chromium', 'edge': 'Microsoft Edge'", "YoutubeDLCookieJar() config = _get_chromium_based_browser_settings(browser_name) if profile is None: search_root =", "SQLITE_AVAILABLE = True except ImportError: # although sqlite3 is part", "struct.unpack(data_format, self.read_bytes(8))[0] def read_cstring(self): buffer = [] while True: c", "_LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return _LinuxDesktopEnvironment.PANTHEON elif xdg_current_desktop ==", "'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'), 'chromium': os.path.join(appdata_local, R'Chromium\\User Data'), 'edge': os.path.join(appdata_local,", "only_once) def error(self, message): if self._ydl: self._ydl.report_error(message) def progress_bar(self): \"\"\"Return", "Safe Storage'], # match 'service' stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) stdout, stderr =", "int((datetime(2001, 1, 1, 0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data,", "def __init__(self, browser_keyring_name, logger, *, keyring=None): self._logger = logger self._v10_key", "_decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) else: self._cookie_counts['other'] += 1 # other prefixes", "_create_progress_bar(logger) as progress_bar: for curr_root, dirs, files in os.walk(root): for", "decrypt v11 cookies: no key found', only_once=True) return None return", "return except BaseException: return printer = MultilinePrinter(file, preserve_output=False) printer.print =", "logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor = get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring)", "cursor.connection.text_factory = bytes column_names = _get_column_names(cursor, 'cookies') secure_column = 'is_secure'", "{counts}') return jar finally: if cursor is not None: cursor.connection.close()", "logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor =", "is_encrypted: value = decryptor.decrypt(encrypted_value) if value is None: return is_encrypted,", "_LinuxKeyring.GNOMEKEYRING return linux_keyring def _get_kwallet_network_wallet(logger): \"\"\" The name of the", "use a python interpreter compiled with sqlite3 support') return YoutubeDLCookieJar()", "data is DPAPI encrypted # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc return _decrypt_windows_dpapi(encrypted_value, self._logger).decode('utf-8') def", "https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.cc SelectBackend \"\"\" desktop_environment = _get_linux_desktop_environment(os.environ) logger.debug(f'detected desktop environment: {desktop_environment.name}')", "return b'' else: logger.debug('password found') if stdout[-1:] == b'\\n': stdout", "to decrypt with DPAPI', only_once=True) return None result = ctypes.string_at(blob_out.pbData,", "auto() GNOMEKEYRING = auto() BASICTEXT = auto() SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys()", "`dbus-monitor` during startup, it can be observed that chromium lists", "v10 cookies: no key found', only_once=True) return None # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_win.cc", "the activate desktop environment [2] Mac: - cookies are either", "p.skip(4, 'unknown record field 1') flags = p.read_uint() is_secure =", "'unknown page header field') with _create_progress_bar(logger) as progress_bar: for i,", "Software\\Opera Stable'), 'vivaldi': os.path.join(appdata_local, R'Vivaldi\\User Data'), }[browser_name] elif sys.platform ==", "0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p = DataParser(data,", "if sys.platform in ('linux', 'linux2'): return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring) elif", "self._logger) else: self._cookie_counts['other'] += 1 return None class MacChromeCookieDecryptor(ChromeCookieDecryptor): def", "*SUPPORTED_KEYRINGS): raise ValueError(f'unsupported keyring: \"{keyring}\"') if profile is not None", "logger.debug(f'NetworkWallet = \"{network_wallet}\"') return network_wallet except Exception as e: logger.warning(f'exception", "the following flags to determine which keyring backend # it", "auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\" KWALLET = auto()", "cannot open sqlite databases if they are already in use", "name_offset = p.read_uint() path_offset = p.read_uint() value_offset = p.read_uint() p.skip(8,", "support profiles') search_root = config['browser_dir'] cookie_database_path = _find_most_recently_used_file(search_root, 'Cookies', logger)", "raise ParserError('reached end of input') data = self._data[self.cursor:end] self.cursor =", "bool(flags & 0x0001) p.skip(4, 'unknown record field 2') domain_offset =", "= _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure", "to decrypt cookie (AES-GCM) because the MAC check failed. Possibly", "QuietMultilinePrinter from .utils import Popen, YoutubeDLCookieJar, error_to_str, expand_path try: import", "as the intended behaviour is to generate a random password", "logger): logger.info('Extracting cookies from firefox') if not SQLITE_AVAILABLE: logger.warning('Cannot extract", "# dbus-monitor \"interface='org.kde.KWallet'\" \"type=method_return\" # while starting chrome. # this", "\"\"\" References: - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc - this data appears to be", "to obtain password from kwallet') if shutil.which('kwallet-query') is None: logger.error('kwallet-query", "False, f'Unknown keyring {keyring}' def _get_mac_keyring_password(browser_keyring_name, logger): logger.debug('using find-generic-password to", "= end return data def expect_bytes(self, expected_value, message): value =", "= os.path.join(tmpdir, 'temporary.sqlite') shutil.copy(database_path, database_copy_path) conn = sqlite3.connect(database_copy_path) return conn.cursor()", "big_endian else '<I' return struct.unpack(data_format, self.read_bytes(4))[0] def read_double(self, big_endian=False): data_format", "except UnicodeDecodeError: logger.warning('failed to parse Safari cookie because UTF-8 decoding", "from {browser_name}{failed_message}') counts = decryptor.cookie_counts.copy() counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version", "passwords. https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/kwallet_dbus.cc KWalletDBus::NetworkWallet which does a dbus call to the", "are skipped during parsing \"\"\" if jar is None: jar", "os.R_OK): jar.load(ignore_discard=True, ignore_expires=True) cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(),", "_open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM", "'win32': appdata_local = os.path.expandvars('%LOCALAPPDATA%') appdata_roaming = os.path.expandvars('%APPDATA%') browser_dir = {", "{keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif keyring", "human readable description of pDataIn None, # pOptionalEntropy: salt? None,", "without sqlite3 support. ' 'Please use a python interpreter compiled", "'safari': return _extract_safari_cookies(profile, logger) elif browser_name in CHROMIUM_BASED_BROWSERS: return _extract_chrome_cookies(browser_name,", "safari cookies database') with open(cookies_path, 'rb') as f: cookies_data =", "offset, description='unknown'): self.skip(offset - self.cursor, description) def skip_to_end(self, description='unknown'): self.skip_to(len(self._data),", "cursor = None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.execute('SELECT host,", "0, 0, tzinfo=timezone.utc) + timedelta(seconds=timestamp)).timestamp()) def _parse_safari_cookies_header(data, logger): p =", "searched') if file == filename: paths.append(os.path.join(curr_root, file)) return None if", "are multiple browser profiles, take the most recently used one", "expected_value: raise ParserError(f'unexpected value: {value} != {expected_value} ({message})') def read_uint(self,", "def _find_most_recently_used_file(root, filename, logger): # if there are multiple browser", "!= 0: logger.error(f'kwallet-query failed with return code {proc.returncode}. Please consult", "context manager with a print method. (Optional)\"\"\" # Do not", "con: col = secretstorage.get_default_collection(con) for item in col.get_all_items(): if item.get_label()", "None def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger): try: plaintext =", "= { 'brave': os.path.join(appdata_local, R'BraveSoftware\\Brave-Browser\\User Data'), 'chrome': os.path.join(appdata_local, R'Google\\Chrome\\User Data'),", "keyring, logger): logger.info(f'Extracting cookies from {browser_name}') if not SQLITE_AVAILABLE: logger.warning(f'Cannot", "counts['unencrypted'] = unencrypted_cookies logger.debug(f'cookie version breakdown: {counts}') return jar finally:", "no key found', only_once=True) return None return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger)", "{browser_name} cookies database in \"{search_root}\"') logger.debug(f'Extracting cookies from: \"{cookie_database_path}\"') decryptor", "the kwallet package for your distribution') return b'' network_wallet =", "datetime, timedelta, timezone from enum import Enum, auto from hashlib", "_LinuxDesktopEnvironment.UNITY elif xdg_current_desktop == 'GNOME': return _LinuxDesktopEnvironment.GNOME elif xdg_current_desktop ==", "= None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes", "for file in files: i += 1 progress_bar.print(f'Searching for \"{filename}\":", "port=None, port_specified=False, domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'), path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False,", "not in browsers_without_profiles } def _extract_chrome_cookies(browser_name, profile, keyring, logger): logger.info(f'Extracting", "but that doesn't matter here. return b'' else: logger.debug('password found')", "path = p.read_cstring() p.skip_to(value_offset) value = p.read_cstring() except UnicodeDecodeError: logger.warning('failed", "None try: cursor = _open_database_copy(cookie_database_path, tmpdir) cursor.connection.text_factory = bytes column_names", "'chrome', 'chromium', 'edge', 'opera', 'vivaldi'} SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox',", "logger.error('no encrypted key in Local State') return None encrypted_key =", "value, path, expiry, is_secure) in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count:", "self._cookie_counts = {'v10': 0, 'other': 0} @staticmethod def derive_key(password): #", "ValueError(f'unknown browser: {browser_name}') def _extract_firefox_cookies(profile, logger): logger.info('Extracting cookies from firefox')", "value = value.decode('utf-8') path = path.decode('utf-8') is_encrypted = not value", "in value def _parse_browser_specification(browser_name, profile=None, keyring=None): if browser_name not in", "logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed.", "GNOME = auto() KDE = auto() PANTHEON = auto() UNITY", "keyring: {keyring.name}') if keyring == _LinuxKeyring.KWALLET: return _get_kwallet_password(browser_keyring_name, logger) elif", "not os.path.isfile(cookies_path): logger.debug('Trying secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if", "blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer) blob_out = DATA_BLOB() ret = ctypes.windll.crypt32.CryptUnprotectData(", "- cookies are either v10 or v11 - v10: AES-CBC", "authentication_tag, self._logger) else: self._cookie_counts['other'] += 1 # any other prefix", "presumably searches for its key in the list. It appears", "self._ydl.params.get('noprogress') or self._ydl.params.get('logger'): return file = self._ydl._out_files['error'] try: if not", "logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. ' 'Please", "= proc.communicate_or_kill() if proc.returncode != 0: logger.error(f'kwallet-query failed with return", "sufficient in all cases. keyring = _LinuxKeyring[keyring] if keyring else", "References: - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata \"\"\" from ctypes.wintypes import DWORD class DATA_BLOB(ctypes.Structure):", "support profiles') if sys.platform != 'darwin': raise ValueError(f'unsupported platform: {sys.platform}')", "p = DataParser(data[body_start:], logger) for page_size in page_sizes: _parse_safari_cookies_page(p.read_bytes(page_size), jar,", "library, it is possible to compile python without # sqlite", "_create_progress_bar(logger): if hasattr(logger, 'progress_bar'): printer = logger.progress_bar() if printer: return", "'kdewallet' try: proc = Popen([ 'dbus-send', '--session', '--print-reply=literal', '--dest=org.kde.kwalletd5', '/modules/kwalletd5',", "read_uint(self, big_endian=False): data_format = '>I' if big_endian else '<I' return", "flags = p.read_uint() is_secure = bool(flags & 0x0001) p.skip(4, 'unknown", "self._logger = logger self._v10_key = self.derive_key(b'peanuts') password = _get_linux_keyring_password(browser_keyring_name, keyring,", "def progress_bar(self): \"\"\"Return a context manager with a print method.", "cookie_jars.append(jar) return _merge_cookie_jars(cookie_jars) def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None): if", "key derivation iterations than linux - not v10: 'old data'", "1 return _decrypt_aes_cbc(ciphertext, self._v10_key, self._logger) elif version == b'v11': self._cookie_counts['v11']", "linux_keyring = _LinuxKeyring.BASICTEXT else: linux_keyring = _LinuxKeyring.GNOMEKEYRING return linux_keyring def", "line in enumerate(table): progress_bar.print(f'Loading cookie {i: 6d}/{total_cookie_count: 6d}') is_encrypted, cookie", "for _ in range(number_of_cookies)] if number_of_cookies == 0: logger.debug(f'a cookies", "= DataParser(data, logger) p.expect_bytes(b'\\x00\\x00\\x01\\x00', 'page signature') number_of_cookies = p.read_uint() record_offsets", "logger) p.skip_to_end('footer') return jar class _LinuxDesktopEnvironment(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h DesktopEnvironment \"\"\"", "DataParser: def __init__(self, data, logger): self._data = data self.cursor =", "in ('linux', 'linux2'): return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return", "paths = 0, [] with _create_progress_bar(logger) as progress_bar: for curr_root,", "cookie: failed_cookies += 1 continue elif not is_encrypted: unencrypted_cookies +=", "'darwin' else 'Chromium', 'opera': 'Opera' if sys.platform == 'darwin' else", "secure=is_secure, expires=expires_utc, discard=False, comment=None, comment_url=None, rest={}) class ChromeCookieDecryptor: \"\"\" Overview:", "secondary cookie location') cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies') if not os.path.isfile(cookies_path): raise", "kwallet-query should be' 'included in the kwallet package for your", "logger): p = DataParser(data, logger) p.expect_bytes(b'cook', 'database signature') number_of_pages =", "logger) elif sys.platform == 'win32': return WindowsChromeCookieDecryptor(browser_root, logger) else: raise", "logger.info(f'Extracted {len(jar)} cookies from safari') return jar class ParserError(Exception): pass", "EVP_AEAD_AES_GCM_TAG_LEN authentication_tag_length = 16 raw_ciphertext = ciphertext nonce = raw_ciphertext[:nonce_length]", "between records') record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger) p.read_bytes(record_length) p.skip_to_end('space in", "0 self._logger = logger def read_bytes(self, num_bytes): if num_bytes <", "not supported on this platform: {sys.platform}') class LinuxChromeCookieDecryptor(ChromeCookieDecryptor): def __init__(self,", "= get_cookie_decryptor(config['browser_dir'], config['keyring_name'], logger, keyring=keyring) with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir: cursor", "an OS protected key (keyring) - v11 keys can be", "def derive_key(password): # values from # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/os_crypt_linux.cc return pbkdf2_sha1(password, salt=b'<PASSWORD>',", "KWallet, # using `dbus-monitor` during startup, it can be observed", "auto() XFCE = auto() class _LinuxKeyring(Enum): \"\"\" https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/key_storage_util_linux.h SelectedLinuxBackend \"\"\"", "in Local State') return None encrypted_key = compat_b64decode(base64_key) prefix =", "else self.derive_key(password) self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0}", "return os.path.expanduser('~/.mozilla/firefox') elif sys.platform == 'win32': return os.path.expandvars(R'%APPDATA%\\Mozilla\\Firefox\\Profiles') elif sys.platform", "value is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0,", "xdg_current_desktop == 'KDE': return _LinuxDesktopEnvironment.KDE elif xdg_current_desktop == 'Pantheon': return", "cursor is not None: cursor.connection.close() def _process_chrome_cookie(decryptor, host_key, name, value,", "i, paths = 0, [] with _create_progress_bar(logger) as progress_bar: for", "is None: return is_encrypted, None return is_encrypted, compat_cookiejar_Cookie( version=0, name=name,", "p = DataParser(data, logger) record_size = p.read_uint() p.skip(4, 'unknown record" ]
[ "os import pytest from hgtools import managers def _ensure_present(mgr): try:", "def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir):", "hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip()", "'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added", "pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def", "baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def", "'-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr =", "mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit',", "yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init',", "content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr)", "'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit',", "mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz:", "'<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m',", "git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config',", "_ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz')", "'-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m',", "tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr)", "as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture", "mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.')", "= managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m',", "_ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with", "with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager()", "mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci',", "<reponame>jaraco/hgtools import os import pytest from hgtools import managers def", "def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz')", "open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return", "return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init')", "pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except", "= managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools')", "'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz',", "tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr =", "os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w')", "mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename): with open(filename,", "def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>')", "baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd):", "baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename):", "mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr", "mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz',", "os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as", "'added content') return tmpdir_as_cwd def touch(filename): with open(filename, 'a'): pass", "open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return", "try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd():", "_ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with", "mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield", "managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar')", "'-am', 'added content') return tmpdir_as_cwd def touch(filename): with open(filename, 'a'):", "'-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am',", "'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content') return tmpdir_as_cwd", "@pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar')", "import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture", "touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz:", "'.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content')", "'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with", "managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed')", "@pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email',", "tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config',", "as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def", "Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture", "with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content')", "managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def", "import os import pytest from hgtools import managers def _ensure_present(mgr):", "'.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w')", "touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed') with open('bar/baz', 'w') as", "mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add',", "mgr._invoke('addremove') mgr._invoke('ci', '-m', 'committed') with open('bar/baz', 'w') as baz: baz.write('content')", "@pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd):", "mgr._invoke('config', 'user.name', 'HGTools') os.makedirs('bar') touch('bar/baz') mgr._invoke('add', '.') mgr._invoke('commit', '-m', 'committed')", "import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version()", "mgr = managers.GitManager() _ensure_present(mgr) mgr._invoke('init') mgr._invoke('config', 'user.email', '<EMAIL>') mgr._invoke('config', 'user.name',", "'committed') with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added", "tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.')", "from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception:", "baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd def touch(filename): with", "mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove') mgr._invoke('ci',", "hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr._invoke('addremove')", "'w') as baz: baz.write('content') mgr._invoke('commit', '-am', 'added content') return tmpdir_as_cwd", "'added content') return tmpdir_as_cwd @pytest.fixture def git_repo(tmpdir_as_cwd): mgr = managers.GitManager()", "except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir", "def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr", "with open('bar/baz', 'w') as baz: baz.write('content') mgr._invoke('ci', '-m', 'added content')" ]
[ "foo SET age = %s, name = %s, created =", "q.query() 'INSERT INTO foo (age, name, created) VALUES (%s, %s,", "\"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO", "= ' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val,", "('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER", "match, pos = matchorfail(sformat, pos + 1) elif sformat[pos] in", "update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update `tables` with", "looks already escaped if paramstyle in ['format', 'pyformat']: if '%'", "\"(\" + x + \")\" if values: _keys = SQLQuery.join(values.keys(),", "token = sformat[tstart:tend] if token[0] in \"([\": level = level", "return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions:", "return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts", "Set `seqname` to the ID if it's not the default,", "to its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True)", "'__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def", "') + \" WHERE \" + where) if _test: return", "SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value) def __add__(self,", "return NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other): if", "(int, long)): where = \"id = \" + sqlparam(where) elif", "NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other,", "return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY',", "<sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id =", "UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently supported: qmark,", "isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'):", "SQLQuery): self.items = list(items.items) else: self.items = [items] # Take", "self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def", "'bob'] \"\"\" def q(x): return \"(\" + x + \")\"", "can be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')')", "WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for", "+ sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE x", "svars = {} where = self._where(where, svars) q = 'DELETE", "+ (nextchar == \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:]))", "instead of interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT", "if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x =", "elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat,", "elif isinstance(val, (list, tuple)) and len(val) == 2: nout =", "3\"> >>> 'WHERE x = ' + sqlquote(True) + '", "table, where, using=None, svars=None, _test=False): \"\"\" Deletes from `table` with", "\"INSERT INTO %s DEFAULT VALUES\" % table def multiple_insert(self, tablename,", "safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t is unicode:", "object to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2'", "form (boolean, string) where boolean says whether string should be", "= \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0", "clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars to", "\"\"\" items = [] items.append('(') for i, v in enumerate(values):", "grouping) def reparam(string_, dictionary): \"\"\" Takes a string and a", "<sql: \"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\" if", "elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items", "_test=False): \"\"\" Inserts multiple rows into `tablename`. The `values` must", "will call reparam for you. Internally, consists of `items`, which", "<sql: 'order_id = 3, cust_id = 2'> >>> sqlwhere({'a': 'a',", "this sort of thing as a clause in any db", "self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return len(self.query())", "if v.keys() != keys: raise ValueError, 'Bad data' sql_query =", "if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for", "raise _ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\", "+ b else: return a or b return xjoin(sql, nout)", "[] elif isinstance(items, list): self.items = items elif isinstance(items, SQLParam):", "\"([\": level = level + 1 elif token[0] in \")]\":", "* FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'>", "%s, name = %s, created = NOW() WHERE name =", "', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ',", "dictionary and interpolates the string using values from the dictionary.", "item in enumerate(items): if i != 0: target_items.append(sep) if isinstance(item,", "= staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x) for", "q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\" s =", "import tokenprog tokenprog = tokenprog def matchorfail(text, pos): match =", "unsupported db paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\"", "the inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor,", "range(out-len(values)+1, out+1) except Exception: out = None if not self.ctx.transactions:", "the hard way... if obj is None: return 'NULL' elif", "it's not the default, or to `False` if there isn't", "return self.query() % tuple([sqlify(x) for x in self.values()]) except (ValueError,", "sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string and returns", "provided, the items are appended to target instead of creating", "def matchorfail(text, pos): match = tokenprog.match(text, pos) if match is", "LIMIT 5'> \"\"\" if svars is None: svars = {}", ">>> db = DB(None, {}) >>> name = 'Joseph' >>>", "2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery):", "_test=_test, **v) for v in values] if seqname is False:", "foo'> >>> db.query(\"SELECT * FROM foo WHERE x = $x\",", "from tokenize import tokenprog tokenprog = tokenprog def matchorfail(text, pos):", ">>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t is", "isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items] #", "other): if isinstance(other, basestring): items = [other] else: return NotImplemented", "True and hash(1) == hash(True)` # we have to do", "a list of dictioanries, one for each row to be", "\"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\">", "s = [] for x in self.items: if isinstance(x, SQLParam):", "`vars` to interpolate it. If `processed=True`, `vars` is a `reparam`-style", ">>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc')", "q.query() 'UPDATE foo SET age = %s, name = %s,", "in enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')')", "the values of the parameters used in the sql query.", "[\"value\"] def __init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'):", "+ ' VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename))", "return obj elif t is str: return obj.decode(encoding) elif t", "+ 1) while pos < len(sformat): if sformat[pos] == \".\"", "= SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.query()", "WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars is", "str: return obj.decode(encoding) elif t in [int, float, bool]: return", "q.query() 'SELECT * FROM test WHERE name=%s' >>> q.values() ['joe']", "WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE name=%s'", "foo WHERE x = \" + sqlquote('f'), _test=True) <sql: \"SELECT", "= 'Joseph' >>> q = db.update('foo', where='name = $name', name='bob',", "for use in a SQL query. >>> 'WHERE x =", "backward compatability, ignore escaping when the query looks already escaped", "x: x = x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self):", "where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from", "pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks", "a list of strings and SQLParams, which get concatenated to", "multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows into", "def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\" %", "items = [other] elif isinstance(other, SQLQuery): items = other.items else:", "float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode):", "where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE", "def __add__(self, other): return self.sqlquery() + other def __radd__(self, other):", "other.items else: return NotImplemented return SQLQuery(self.items + items) def __radd__(self,", "sformat[dollar + 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos,", "= reparam(where, svars) return where def select(self, tables, svars=None, what='*',", "SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) #", "is None: raise _ItplError(text, pos) return match, match.end() namechars =", "in self.items if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None,", "\".\" and \\ pos + 1 < len(sformat) and sformat[pos", "clause `where` (interpolated using `vars`) and setting `values`. >>> db", "like a WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>>", "_test=True) <sql: \"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'),", "target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ')", "= x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns", "if isinstance(sql_query, tuple): # for some databases, a separate query", "and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value)", "'t' AND y = 3\"> >>> 'WHERE x = '", "match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos", "%s, created = NOW() WHERE name = %s' >>> q.values()", "* FROM test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM", "all rows have same keys. for v in values: if", "sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because `1 ==", "\"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v", "`sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\"", "strings and SQLParams, which get concatenated to produce the actual", "== 'WHERE': nout = 'id = ' + sqlquote(val) else:", "target instead of creating a new SQLQuery. \"\"\" if target", "def _where(self, where, svars): if isinstance(where, (int, long)): where =", "list to use instead of interpolating. >>> db = DB(None,", "SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other, basestring): items", "{} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset)", "email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values:", "tend = match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\":", "sformat[pos:dollar + 1])) pos = dollar + 1 + (nextchar", "have same keys. for v in values: if v.keys() !=", "return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3])", "IN $s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\"", "where = \"id = \" + sqlparam(where) elif isinstance(where, (list,", "SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql:", "`values` must be a list of dictioanries, one for each", "q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is None: svars", "2-tuples of the form (boolean, string) where boolean says whether", "and a dictionary and interpolates the string using values from", "= other.items else: return NotImplemented return SQLQuery(self.items + items) def", "\"\"\" Takes a string and a dictionary and interpolates the", "+ ' AND y IN ' + sqlquote([2, 3]) <sql:", "r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q", "[] for x in self.items: if isinstance(x, SQLParam): x =", "def xjoin(a, b): if a and b: return a +", "'numeric': return ':1' elif paramstyle is None or paramstyle in", "return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a", "TypeError): return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return", "the items are appended to target instead of creating a", "+ sqlquote([2, 3]) <sql: \"WHERE x = 't' AND y", "where, using=None, svars=None, _test=False): \"\"\" Deletes from `table` with clauses", "#coding:utf8 ''' Created on 2013-8-21 @author: lan (www.9miao.com) ''' import", "unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj,", "\"\"\" t = type(obj) if t is unicode: return obj", "\"}\": level = level - 1 chunks.append((1, sformat[dollar + 2:pos", "\"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value = value", "in enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for", "obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the", "string and returns a list of 2-tuples of the form", "+ sqlwhere(values, ', ') + \" WHERE \" + where)", "inserted, each with the same set of keys. Returns the", "len(sformat) and sformat[pos + 1] in namechars: match, pos =", "' + sqllist(using) if where: q += ' WHERE '", "'t' AND y IN (2, 3)\"> \"\"\" if isinstance(a, list):", "False: return None else: return out keys = values[0].keys() #@@", "\"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True)", "token == \"}\": level = level - 1 chunks.append((1, sformat[dollar", "' + sqlquote(3) <sql: \"WHERE x = 't' AND y", "in ['format', 'pyformat']: if '%' in x and '%%' not", "is a `reparam`-style list to use instead of interpolating. >>>", "return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def", "query. \"\"\" __slots__ = [\"items\"] # tested in sqlquote's docstring", "group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables` with", "('bar', '<EMAIL>')\"> \"\"\" if not values: return [] if not", "`using`. >>> db = DB(None, {}) >>> name = 'Joe'", "if not self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where,", "<sql: \"WHERE x = 't' AND y = 3\"> >>>", "u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if t", "for x in self.values()]) except (ValueError, TypeError): return self.query() def", ">>> q.values() ['joe'] \"\"\" return [i.value for i in self.items", "current sequence ID. Set `seqname` to the ID if it's", "way... if obj is None: return 'NULL' elif obj is", "list of dictioanries, one for each row to be inserted,", "db = DB(None, {}) >>> q = db.insert('foo', name='bob', age=2,", "['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value =", "\"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person", "Converts any given object to unicode string. >>> safeunicode('hello') u'hello'", "target_items.append(suffix) return target join = staticmethod(join) def _str(self): try: return", "y IN ' + sqlquote([2, 3]) <sql: \"WHERE x =", "\"\"\" Inserts multiple rows into `tablename`. The `values` must be", "db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return", "def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the", "and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query", "sure all rows have same keys. for v in values:", "`tablename`. Returns current sequence ID. Set `seqname` to the ID", "where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET',", "SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql:", "automatically escape % characters in the query # For backward", "b): if a and b: return a + ' '", "svars=None): \"\"\" Execute SQL query `sql_query` using dictionary `vars` to", "get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif paramstyle", "__init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos = pos", "id of the inserted row. q1, q2 = sql_query self._db_execute(db_cursor,", "values: return [] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname,", "# the id of the inserted row. q1, q2 =", "`vars`) and setting `values`. >>> db = DB(None, {}) >>>", "+ 1 elif token[0] in \")]\": level = level -", "'a = %s AND b = %s' \"\"\" return SQLQuery.join([k", "'.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1,", "+ self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return '<param:", "using `vars`) and setting `values`. >>> db = DB(None, {})", "if dollar < 0: break nextchar = sformat[dollar + 1]", "sformat.find(\"$\", pos) if dollar < 0: break nextchar = sformat[dollar", "_ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos", "= level - 1 chunks.append((1, sformat[dollar + 2:pos - 1]))", "<sql: \"INSERT INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar',", "return a or b return xjoin(sql, nout) def _where(self, where,", "'order_id = 3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b':", "def values(self): \"\"\" Returns the values of the parameters used", "[] for live, chunk in _interpolate(string_): if live: v =", "elif t is str: return obj.decode(encoding) elif t in [int,", "* FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM", "compatability, ignore escaping when the query looks already escaped if", "with clauses `where` and `using`. >>> db = DB(None, {})", "the inserted rows. Set `seqname` to the ID if it's", "query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table,", "in self.values()]) except (ValueError, TypeError): return self.query() def __str__(self): return", "VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age,", "2013-8-21 @author: lan (www.9miao.com) ''' import itertools import datetime def", ">>> db = DB(None, {}) >>> name = 'Joe' >>>", "return NotImplemented return SQLQuery(self.items + items) def __radd__(self, other): if", "and `offset`. Uses vars to interpolate. Otherwise, each clause can", "k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test:", "an `SQLQuery` for the result. >>> reparam(\"s = $s\", dict(s=True))", "def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery() +", "\"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\">", "# backwards-compatibility elif isinstance(val, SQLQuery): nout = val else: nout", "= [self.gen_clause(sql, val, svars) for sql, val in sql_clauses if", "sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary` to an", "') sql_query = \"INSERT INTO %s \" % tablename +", "`values` into `tablename`. Returns current sequence ID. Set `seqname` to", "the parameters used in the sql query. >>> q =", "db paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\" pass", "Takes a string and a dictionary and interpolates the string", "= ' + sqlquote(3) <sql: \"WHERE x = 't' AND", "WHERE name = 'Joe'\"> \"\"\" if svars is None: svars", "not values: return [] if not self.supports_multiple_insert: out = [self.insert(tablename,", "row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else:", "( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>>", "clause in any db function. Otherwise, you can pass a", "the sql query. >>> q = SQLQuery([\"SELECT * FROM test", "= 'f'\"> \"\"\" if svars is None: svars = {}", "\"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\"", "' AND y IN ' + sqlquote([2, 3]) <sql: \"WHERE", "== hash(True)` # we have to do this the hard", "FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test", "VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return", "import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object", "[2, 'bob'] \"\"\" def q(x): return \"(\" + x +", "on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools import datetime", "tstart, tend = match.regs[3] token = sformat[tstart:tend] if token ==", "break nextchar = sformat[dollar + 1] if nextchar == \"{\":", "+ 1] in namechars: match, pos = matchorfail(sformat, pos +", "returns a list of 2-tuples of the form (boolean, string)", "from `tables` with clauses `where`, `order`, `group`, `limit`, and `offset`.", "= SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) == 2:", "# iterator return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj):", "if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return", "SET \" + sqlwhere(values, ', ') + \" WHERE \"", "in \"([\": level = level + 1 elif token[0] in", "< len(sformat): if sformat[pos] == \".\" and \\ pos +", "self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else:", "self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\"", "'Joseph'] \"\"\" if svars is None: svars = {} where", "to utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4'", "is not None] qout = SQLQuery.join(clauses) if _test: return qout", "dictionary): \"\"\" Takes a string and a dictionary and interpolates", ">>> db = DB(None, {}) >>> db.query(\"SELECT * FROM foo\",", "test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM", "<sql: 'a, b'> Optinally, prefix and suffix arguments can be", "obj elif t is str: return obj.decode(encoding) elif t in", "`a` is quoted properly for use in a SQL query.", "sformat[dollar + 2:pos - 1])) elif nextchar in namechars: chunks.append((0,", "Take care of SQLLiterals for i, item in enumerate(self.items): if", "else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1,", ">>> q = db.update('foo', where='name = $name', name='bob', age=2, ...", "'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM", "'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age, name, created)", "query has to be made to find # the id", "= [] for live, chunk in _interpolate(string_): if live: v", "paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def", "= tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos) if", "is unicode: return obj elif t is str: return obj.decode(encoding)", "WHERE x = \" + sqlquote('f'), _test=True) <sql: \"SELECT *", "safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if", "other): return other + self.sqlquery() def __str__(self): return str(self.value) def", "= 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id", "values.values()], ', ') sql_query = \"INSERT INTO %s \" %", "self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items = [other]", "if isinstance(lst, basestring): return lst else: return ', '.join(lst) def", "return sql_query def sql_clauses(self, what, tables, where, group, order, limit,", "\"\"\" Inserts `values` into `tablename`. Returns current sequence ID. Set", "where = reparam(where, svars) return where def select(self, tables, svars=None,", "pos) if dollar < 0: break nextchar = sformat[dollar +", "interpolates the string using values from the dictionary. Returns an", "the actual query. \"\"\" __slots__ = [\"items\"] # tested in", "2, 3]) <sql: '(1, 2, 3)'> \"\"\" items = []", "svars = {} if not processed and not isinstance(sql_query, SQLQuery):", "**values): \"\"\" Inserts `values` into `tablename`. Returns current sequence ID.", "not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v", "test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value", "out+1) except Exception: out = None if not self.ctx.transactions: self.ctx.commit()", "':1' elif paramstyle is None or paramstyle in ['format', 'pyformat']:", "WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE", "'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\",", "if where: q += ' WHERE ' + where return", "%s at char %d\" % ( repr(self.text), self.pos) class SQLParam(object):", "WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items", "else: return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2,", "= tokenprog.match(text, pos) if match is None: raise _ItplError(text, pos)", "`where` and `using`. >>> db = DB(None, {}) >>> name", "there isn't one. >>> db = DB(None, {}) >>> q", "query # For backward compatability, ignore escaping when the query", "bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars", "i, item in enumerate(items): if i != 0: target_items.append(sep) if", "SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles", "elif token == \"}\": level = level - 1 chunks.append((1,", "FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\"", "and len(val) == 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility", "not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def", "tokenprog tokenprog = tokenprog def matchorfail(text, pos): match = tokenprog.match(text,", "* FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'>", "ID. Set `seqname` to the ID if it's not the", "dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\" dictionary =", "= dollar + 2, 1 while level: match, pos =", "and len(where) == 2: where = SQLQuery(where[0], where[1]) elif isinstance(where,", "enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k", "'(1, 2, 3)'> \"\"\" items = [] items.append('(') for i,", "insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`.", "keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query", "`False` if there isn't one. >>> db = DB(None, {})", "of the sql query. >>> q = SQLQuery([\"SELECT * FROM", "age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo", "'<param: %s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\"", "\"\"\" from tokenize import tokenprog tokenprog = tokenprog def matchorfail(text,", "FROM foo WHERE x = 'f'\"> \"\"\" if svars is", "not None] qout = SQLQuery.join(clauses) if _test: return qout return", "in %s at char %d\" % ( repr(self.text), self.pos) class", "one for each row to be inserted, each with the", "None: svars = {} where = self._where(where, svars) query =", "escaped if paramstyle in ['format', 'pyformat']: if '%' in x", "= value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return", "matchorfail(text, pos): match = tokenprog.match(text, pos) if match is None:", "a dictionary to the keyword argument `vars` and the function", "suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor() if seqname", "= x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically escape", "xjoin(a, b): if a and b: return a + '", "= SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO", "ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES", "in a SQL query. >>> 'WHERE x = ' +", "hash(1) == hash(True)` # we have to do this the", "%s AND b = %s' \"\"\" return SQLQuery.join([k + '", "sql_query def sql_clauses(self, what, tables, where, group, order, limit, offset):", "SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self, what,", "['joe'] \"\"\" return [i.value for i in self.items if isinstance(i,", "\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while 1: dollar", "%s DEFAULT VALUES\" % table def multiple_insert(self, tablename, values, seqname=None,", "using=None, svars=None, _test=False): \"\"\" Deletes from `table` with clauses `where`", "For backward compatability, ignore escaping when the query looks already", "in values.values()], ', ') sql_query = \"INSERT INTO %s \"", "None] qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout,", "isinstance(items, list): self.items = items elif isinstance(items, SQLParam): self.items =", "'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id = 2'>", "svars) query = ( \"UPDATE \" + sqllist(tables) + \"", "\"\"\" Converts a `dictionary` to an SQL WHERE clause `SQLQuery`.", "appended to target instead of creating a new SQLQuery. \"\"\"", "return target join = staticmethod(join) def _str(self): try: return self.query()", "+ q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self,", "def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif", "is None: svars = {} where = self._where(where, svars) query", "out = range(out-len(values)+1, out+1) except Exception: out = None if", "multiple rows into `tablename`. The `values` must be a list", "DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT", "+ 1, 1 while level: match, pos = matchorfail(sformat, pos)", "interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT * FROM", "`obj` to its proper SQL version >>> sqlify(None) 'NULL' >>>", "quoted properly for use in a SQL query. >>> 'WHERE", "#@@ make sure all keys are valid # make sure", "( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group),", "= 'Joe'\"> \"\"\" if svars is None: svars = {}", "is quoted properly for use in a SQL query. >>>", "3]) <sql: '(1, 2, 3)'> \"\"\" items = [] items.append('(')", "False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat())", "return str(obj) def sqlify(obj): \"\"\" converts `obj` to its proper", "return NotImplemented return self def __len__(self): return len(self.query()) def query(self,", "processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return", "return \"INSERT INTO %s DEFAULT VALUES\" % table def multiple_insert(self,", "return '<param: %s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object):", "FROM foo WHERE x = \" + sqlquote('f'), _test=True) <sql:", "self.sql_clauses(what, tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql,", "VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def", "separate query has to be made to find # the", "result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported", "\")\" if values: _keys = SQLQuery.join(values.keys(), ', ') _values =", "= [items] # Take care of SQLLiterals for i, item", "'order_id = 3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2,", "1 elif token[0] in \")]\": level = level - 1", "of interpolating. >>> db = DB(None, {}) >>> db.query(\"SELECT *", "elif paramstyle == 'numeric': return ':1' elif paramstyle is None", "q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out =", "vars to interpolate. Otherwise, each clause can be a SQLQuery.", "try: return self.query() % tuple([sqlify(x) for x in self.values()]) except", "while pos < len(sformat): if sformat[pos] == \".\" and \\", "level + 1 elif token[0] in \")]\": level = level", "Returns the list of ids of the inserted rows. Set", "+ ' AND y = ' + sqlquote(3) <sql: \"WHERE", "% repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You can", "' % (tablename, ', '.join(keys))) for i, row in enumerate(values):", "reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'>", "SQL query `sql_query` using dictionary `vars` to interpolate it. If", "if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj", ">>> reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\"> >>>", "Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test", "pos = 0 while 1: dollar = sformat.find(\"$\", pos) if", "= values[0].keys() #@@ make sure all keys are valid #", "ValueError.__init__(self) self.text = text self.pos = pos def __str__(self): return", "WHERE x = 'f'\"> \"\"\" if svars is None: svars", "SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target join", "dictioanries, one for each row to be inserted, each with", "for i, item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value,", "repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You can pass", "\"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM", "= \" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo", "for i, row in enumerate(values): if i != 0: sql_query.append(\",", "= level + 1 elif token[0] in \")]\": level =", "chunk in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v))", "FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT *", "if there isn't one. >>> db = DB(None, {}) >>>", ">>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\"", "if svars is None: svars = {} sql_clauses = self.sql_clauses(what,", "qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self,", "for use in something like a WHERE clause. >>> sqllist(['a',", "', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql:", "def reparam(string_, dictionary): \"\"\" Takes a string and a dictionary", "tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos) if match", ">>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None: self.items", "name = 'bob', created = NOW() WHERE name = 'Joseph'\">", "\"\"\" You can pass this sort of thing as a", "limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars): if isinstance(val,", "_interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk)", "= self._where(where, svars) q = 'DELETE FROM ' + table", "dollar = sformat.find(\"$\", pos) if dollar < 0: break nextchar", "Otherwise, each clause can be a SQLQuery. >>> db =", "else: return NotImplemented return self def __len__(self): return len(self.query()) def", "\\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while 1:", "\"\"\" Ensures `a` is quoted properly for use in a", "`items`, which is a list of strings and SQLParams, which", "format string and returns a list of 2-tuples of the", "a SQLQuery. >>> db = DB(None, {}) >>> db.select('foo', _test=True)", "Optinally, prefix and suffix arguments can be provided. >>> SQLQuery.join(['a',", "of 2-tuples of the form (boolean, string) where boolean says", "tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new", "nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout", "\"WHERE x = 't' AND y = 3\"> >>> 'WHERE", "paramstyle == 'numeric': return ':1' elif paramstyle is None or", "isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value): self.items.append(value) def", "(nextchar == \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return", "__init__(self, v): self.v = v def __repr__(self): return self.v class", "== \"{\": level = level + 1 elif token ==", "nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) ==", "if it's not the default, or to `False` if there", "b)'> If target argument is provided, the items are appended", "def __init__(self): \"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False,", ">>> q <sql: \"UPDATE foo SET age = 2, name", "and setting `values`. >>> db = DB(None, {}) >>> name", "characters in the query # For backward compatability, ignore escaping", "SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3)", "(interpolated using `vars`) and setting `values`. >>> db = DB(None,", "isn't one. >>> db = DB(None, {}) >>> db.supports_multiple_insert =", "inserted rows. Set `seqname` to the ID if it's not", "- 1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar", "% (tablename, ', '.join(keys))) for i, row in enumerate(values): if", "def __radd__(self, other): return other + self.sqlquery() def __str__(self): return", "of the inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1)", "FROM test WHERE name=?' \"\"\" s = [] for x", "any given object to utf-8 encoded string. >>> safestr('hello') 'hello'", "pos = matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\":", "join = staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x)", "return where def select(self, tables, svars=None, what='*', where=None, order=None, group=None,", "[self.gen_clause(sql, val, svars) for sql, val in sql_clauses if val", "FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT", ">>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\" items", "2, name = 'bob', created = NOW() WHERE name =", "q <sql: 'SELECT * FROM test WHERE x=1'> >>> q.query(),", "_test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM", "tokenprog.match(text, pos) if match is None: raise _ItplError(text, pos) return", "whether string should be evaled or not. from <http://lfw.org/python/Itpl.py> (public", "(boolean, string) where boolean says whether string should be evaled", "SQLLiterals for i, item in enumerate(self.items): if isinstance(item, SQLParam) and", "_where(self, where, svars): if isinstance(where, (int, long)): where = \"id", "\"\"\" if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def", "person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if", "where, svars): if isinstance(where, (int, long)): where = \"id =", "other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items)", "x=1'> >>> q.query(), q.values() ('SELECT * FROM test WHERE x=%s',", "+ ' ' + b else: return a or b", "AND b = %s' \"\"\" return SQLQuery.join([k + ' =", "x = x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\"", "db = DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT *", "safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t", "chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos", "def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using", "IN (1, 2)'> \"\"\" dictionary = dictionary.copy() # eval mucks", "return \"\".join(s) def values(self): \"\"\" Returns the values of the", "if token == \"{\": level = level + 1 elif", "parameters used in the sql query. >>> q = SQLQuery([\"SELECT", "( \"UPDATE \" + sqllist(tables) + \" SET \" +", "pos def __str__(self): return \"unfinished expression in %s at char", "q(_keys) + ' VALUES ' + q(_values) else: sql_query =", "= dictionary.copy() # eval mucks with it result = []", "{\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT", "obj is False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime):", "match, pos = matchorfail(sformat, dollar + 1) while pos <", "{}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT *", "elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator", "svars = {} sql_clauses = self.sql_clauses(what, tables, where, group, order,", "in SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test WHERE", "= 't' AND y IN (2, 3)\"> \"\"\" if isinstance(a,", "' ' + b else: return a or b return", "if not values: return [] if not self.supports_multiple_insert: out =", "<sql: \"SELECT * FROM foo WHERE x = 'f'\"> >>>", "= obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the arguments", "(1, 2)'> \"\"\" dictionary = dictionary.copy() # eval mucks with", "level = level + 1 elif token == \"}\": level", "\"\"\" Execute SQL query `sql_query` using dictionary `vars` to interpolate", "x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically escape %", "isinstance(where, (int, long)): where = \"id = \" + sqlparam(where)", "pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self)", "[2, 'bob', 'Joseph'] \"\"\" if svars is None: svars =", "__repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a", "3)'> \"\"\" items = [] items.append('(') for i, v in", "[items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items =", "be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql:", "a format string and returns a list of 2-tuples of", "self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self", "= self.sql_clauses(what, tables, where, group, order, limit, offset) clauses =", "= 'Joseph'\"> >>> q.query() 'UPDATE foo SET age = %s,", "= SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True) def", "are valid # make sure all rows have same keys.", "its proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\"", "pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token[0]", "svars) return where def select(self, tables, svars=None, what='*', where=None, order=None,", "= \" + sqlparam(where) elif isinstance(where, (list, tuple)) and len(where)", "_test=True) <sql: \"SELECT * FROM foo WHERE x = 'f'\">", "elif sformat[pos] in \"([\": pos, level = pos + 1,", "paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery()", "q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table):", "1 < len(sformat) and sformat[pos + 1] in namechars: match,", "'?' elif paramstyle == 'numeric': return ':1' elif paramstyle is", "suffix: target_items.append(suffix) return target join = staticmethod(join) def _str(self): try:", "'<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a string", "list of 2-tuples of the form (boolean, string) where boolean", "FROM foo WHERE name = 'Joe'\"> \"\"\" if svars is", "b return xjoin(sql, nout) def _where(self, where, svars): if isinstance(where,", "isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return obj elif", "'SELECT * FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\"", "`table` with clauses `where` and `using`. >>> db = DB(None,", "def __repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\"", "while 1: dollar = sformat.find(\"$\", pos) if dollar < 0:", "from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize import", "svars): if isinstance(val, (int, long)): if sql == 'WHERE': nout", "be a SQLQuery. >>> db = DB(None, {}) >>> db.select('foo',", "'\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding)", "query looks already escaped if paramstyle in ['format', 'pyformat']: if", "'NOW()'> \"\"\" def __init__(self, v): self.v = v def __repr__(self):", "if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar", "matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if", "FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return", "= 2, name = 'bob', created = NOW() WHERE name", ">>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v =", "pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping='", "elif isinstance(where, SQLQuery): pass else: where = reparam(where, svars) return", "DB(None, {}) >>> name = 'Joseph' >>> q = db.update('foo',", "keys are valid # make sure all rows have same", "age = 2, name = 'bob', created = NOW() WHERE", "* FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT", "sqlquote(a): \"\"\" Ensures `a` is quoted properly for use in", "= {} where = self._where(where, svars) query = ( \"UPDATE", "isinstance(lst, basestring): return lst else: return ', '.join(lst) def _sqllist(values):", "for i, v in enumerate(values): if i != 0: items.append(',", "keys. for v in values: if v.keys() != keys: raise", "of the inserted rows. Set `seqname` to the ID if", "`where` (interpolated using `vars`) and setting `values`. >>> db =", "sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" #", ">>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.values()", "table): return \"INSERT INTO %s DEFAULT VALUES\" % table def", "<sql: '(1, 2, 3)'> \"\"\" items = [] items.append('(') for", "'Joseph' >>> q = db.update('foo', where='name = $name', name='bob', age=2,", "x = 't' AND y IN (2, 3)\"> \"\"\" if", "\"\"\" # because `1 == True and hash(1) == hash(True)`", "level: match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3]", "FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM", ">>> db = DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT", "= sformat[tstart:tend] if token == \"{\": level = level +", "must be a list of dictioanries, one for each row", "return obj.decode(encoding) elif t in [int, float, bool]: return unicode(obj)", "+ sqllist(tables) + \" SET \" + sqlwhere(values, ', ')", "= %s' \"\"\" return SQLQuery.join([k + ' = ' +", "isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x)", "tokenize import tokenprog tokenprog = tokenprog def matchorfail(text, pos): match", "= NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo", "try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception:", "+ 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level", "\"\"\" if items is None: self.items = [] elif isinstance(items,", "SQL query. >>> 'WHERE x = ' + sqlquote(True) +", "(currently supported: qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError):", "`sql_query` using dictionary `vars` to interpolate it. If `processed=True`, `vars`", "rows have same keys. for v in values: if v.keys()", "* FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\"", "SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None: self.items =", "# eval mucks with it result = [] for live,", "def q(x): return \"(\" + x + \")\" if values:", "the arguments for use in something like a WHERE clause.", "def __add__(self, other): if isinstance(other, basestring): items = [other] elif", "using dictionary `vars` to interpolate it. If `processed=True`, `vars` is", "nout = 'id = ' + sqlquote(val) else: nout =", "proper SQL version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>>", "< 0: break nextchar = sformat[dollar + 1] if nextchar", "dictionary.copy() # eval mucks with it result = [] for", "for live, chunk in _interpolate(string_): if live: v = eval(chunk,", "in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery.", "x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo", "match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = []", "created = NOW() WHERE name = %s' >>> q.values() [2,", "'UPDATE foo SET age = %s, name = %s, created", "name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE name=%s'", "as a clause in any db function. Otherwise, you can", ">>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'>", "1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar +", "' + b else: return a or b return xjoin(sql,", "= SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout =", "\" + sqlwhere(values, ', ') + \" WHERE \" +", "q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor,", "= SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ',", "NOW() WHERE name = %s' >>> q.values() [2, 'bob', 'Joseph']", "table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple", "values] if seqname is False: return None else: return out", "class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text = text", "class SQLQuery(object): \"\"\" You can pass this sort of thing", "if a and b: return a + ' ' +", "target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for", "**v) for v in values] if seqname is False: return", "= pos + 1, 1 while level: match, pos =", "isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\"", "= [\"items\"] # tested in sqlquote's docstring def __init__(self, items=None):", "items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>>", "', ') <sql: 'a, b'> Optinally, prefix and suffix arguments", "to `False` if there isn't one. >>> db = DB(None,", "hash(True)` # we have to do this the hard way...", "= dollar + 1 + (nextchar == \"$\") if pos", "+ 1 < len(sformat) and sformat[pos + 1] in namechars:", "of thing as a clause in any db function. Otherwise,", "return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql:", ">>> db = DB(None, {}) >>> db.supports_multiple_insert = True >>>", "sformat[tstart:tend] if token[0] in \"([\": level = level + 1", "return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT", "name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\"", "safestr(x) # automatically escape % characters in the query #", "== \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2,", "foo\", _test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT *", "with the same set of keys. Returns the list of", "match.regs[3] token = sformat[tstart:tend] if token == \"{\": level =", "pos = dollar + 1 + (nextchar == \"$\") if", "value): self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle ==", "if seqname is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname)", "False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): #", "\"\"\" s = [] for x in self.items: if isinstance(x,", ">>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\":", "None: return 'NULL' elif obj is True: return \"'t'\" elif", "use instead of interpolating. >>> db = DB(None, {}) >>>", "if not processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query,", ">>> name = 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(),", "'b': 'b'}).query() 'a = %s AND b = %s' \"\"\"", "val, svars) for sql, val in sql_clauses if val is", "dictionary. Returns an `SQLQuery` for the result. >>> reparam(\"s =", "sql == 'WHERE': nout = 'id = ' + sqlquote(val)", "where boolean says whether string should be evaled or not.", "return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string and", "query `sql_query` using dictionary `vars` to interpolate it. If `processed=True`,", ">>> q.query() 'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark')", "[] pos = 0 while 1: dollar = sformat.find(\"$\", pos)", "- 1 else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0,", "seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns current", "+ \" SET \" + sqlwhere(values, ', ') + \"", "this the hard way... if obj is None: return 'NULL'", "('SELECT * FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql:", "sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and", "db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'],", "of keys. Returns the list of ids of the inserted", "\" + sqllist(tables) + \" SET \" + sqlwhere(values, ',", "+ 2:pos - 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar]))", "docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\")", "= sformat.find(\"$\", pos) if dollar < 0: break nextchar =", "sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE x =", "'%%' not in x: x = x.replace('%', '%%') s.append(x) return", "match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\": level =", "argument `vars` and the function will call reparam for you.", "= [items] elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items", "= bar.id LIMIT 5'> \"\"\" if svars is None: svars", "isinstance(sql_query, tuple): # for some databases, a separate query has", "= ' + sqlquote(True) + ' AND y IN '", "SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in values.values()],", "vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET age =", "tokenprog = tokenprog def matchorfail(text, pos): match = tokenprog.match(text, pos)", "of strings and SQLParams, which get concatenated to produce the", "return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query part", "_keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v", "INTO %s \" % tablename + q(_keys) + ' VALUES", "+ where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor,", "1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos =", "in the query # For backward compatability, ignore escaping when", "', ', prefix='(', suffix=')') <sql: '(a, b)'> If target argument", "pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token =", "__radd__(self, other): if isinstance(other, basestring): items = [other] else: return", "if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst):", "the ID if it's not the default, or to `False`", "SQLQuery. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\",", "ignore escaping when the query looks already escaped if paramstyle", "def append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring):", "says whether string should be evaled or not. from <http://lfw.org/python/Itpl.py>", "SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val) == 2: nout", "SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT * FROM ',", "'b'}).query() 'a = %s AND b = %s' \"\"\" return", "any db function. Otherwise, you can pass a dictionary to", "for you. Internally, consists of `items`, which is a list", "self.query() % tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError):", "tuple)) and len(val) == 2: nout = SQLQuery(val[0], val[1]) #", "in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] =", "* FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>> q", "a new SQLQuery. \"\"\" if target is None: target =", "2])) <sql: 's IN (1, 2)'> \"\"\" dictionary = dictionary.copy()", ">>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?' \"\"\" s", "* FROM foo WHERE x = \" + sqlquote('f'), _test=True)", "= [other] else: return NotImplemented return SQLQuery(items + self.items) def", "\"UPDATE \" + sqllist(tables) + \" SET \" + sqlwhere(values,", "len(where) == 2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery):", "% repr(str(self)) class SQLLiteral: \"\"\" Protects a string from `sqlquote`.", "None: svars = {} if not processed and not isinstance(sql_query,", "not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple):", "if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def", "obj) else: return str(obj) def sqlify(obj): \"\"\" converts `obj` to", "') _values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ')", "clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3", "db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"},", "def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other,", "<sql: \"WHERE x = 't' AND y IN (2, 3)\">", "foo SET age = 2, name = 'bob', created =", "out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out", "for v in values.values()], ', ') sql_query = \"INSERT INTO", "return qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False,", "in values] if seqname is False: return None else: return", "return \"(\" + x + \")\" if values: _keys =", "sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out", "if sql == 'WHERE': nout = 'id = ' +", "and hash(1) == hash(True)` # we have to do this", "\"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql:", "= bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo, bar", "If target argument is provided, the items are appended to", "where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo,", "= reparam(val, svars) def xjoin(a, b): if a and b:", "a or b return xjoin(sql, nout) def _where(self, where, svars):", "'bob', created = NOW() WHERE name = 'Joseph'\"> >>> q.query()", "datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode):", "for k, v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\"", "= ( \"UPDATE \" + sqllist(tables) + \" SET \"", "q += ' WHERE ' + where return q sqlproducer", "order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars):", "sqlwhere(values, ', ') + \" WHERE \" + where) if", "\"\"\" if isinstance(lst, basestring): return lst else: return ', '.join(lst)", "the default, or to `False` if there isn't one. >>>", "and b: return a + ' ' + b else:", "return self.sqlquery() + other def __radd__(self, other): return other +", "\"\"\" if svars is None: svars = {} if not", "# for some databases, a separate query has to be", "self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark':", "v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self):", "AND '): \"\"\" Converts a `dictionary` to an SQL WHERE", "can be a SQLQuery. >>> db = DB(None, {}) >>>", "+ 1 elif token == \"}\": level = level -", "2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else:", "if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else:", "`values`. >>> db = DB(None, {}) >>> name = 'Joseph'", "tablename + q(_keys) + ' VALUES ' + q(_values) else:", "where = self._where(where, svars) query = ( \"UPDATE \" +", "= None if not self.ctx.transactions: self.ctx.commit() return out def update(self,", "sqlquote(3) <sql: \"WHERE x = 't' AND y = 3\">", ">>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\"", "_test=False, **values): \"\"\" Update `tables` with clause `where` (interpolated using", "SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for i, item", "has to be made to find # the id of", "__iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery):", "pos = matchorfail(sformat, dollar + 1) while pos < len(sformat):", "dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\"", "= 0 while 1: dollar = sformat.find(\"$\", pos) if dollar", "\"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql:", "__repr__(self): return '<param: %s>' % repr(self.value) sqlparam = SQLParam class", "y IN (2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a)", "self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts", "db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True)", "''' Created on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools", "= DB(None, {}) >>> db.supports_multiple_insert = True >>> values =", ">>> q.query() 'INSERT INTO foo (age, name, created) VALUES (%s,", "'DELETE FROM ' + table if using: q += '", "'qmark': return '?' elif paramstyle == 'numeric': return ':1' elif", "domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog =", "return SQLQuery.join([k + ' = ' + sqlparam(v) for k,", "target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target join =", "tend = match.regs[3] token = sformat[tstart:tend] if token == \"{\":", "\"SELECT * FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT", ">>> 'WHERE x = ' + sqlquote(True) + ' AND", "mucks with it result = [] for live, chunk in", "q += ' USING ' + sqllist(using) if where: q", "level = level + 1 elif token[0] in \")]\": level", "SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for i in", "v in enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v))", "self.items = items elif isinstance(items, SQLParam): self.items = [items] elif", "repr(str(self)) class SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>>", "' VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return", "in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a string", "'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\"", "(2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else: return", "if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None):", "for sql, val in sql_clauses if val is not None]", "2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND", "token == \"{\": level = level + 1 elif token", "expression in %s at char %d\" % ( repr(self.text), self.pos)", "is None: svars = {} if not processed and not", "= %s AND b = %s' \"\"\" return SQLQuery.join([k +", "SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items = list(items.items)", "\"\"\" Converts the arguments for use in something like a", "% tablename + q(_keys) + ' VALUES ' + q(_values)", "Ensures `a` is quoted properly for use in a SQL", "suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'], ', ',", "= DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'),", "is None: svars = {} where = self._where(where, svars) q", ">>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3,", "group, order, limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)),", "else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given", "i, row in enumerate(values): if i != 0: sql_query.append(\", \")", "you. Internally, consists of `items`, which is a list of", "tables, where, group, order, limit, offset): return ( ('SELECT', what),", "r\"\"\" Converts any given object to utf-8 encoded string. >>>", "basestring): return lst else: return ', '.join(lst) def _sqllist(values): \"\"\"", "version >>> sqlify(None) 'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3'", "+ 2, 1 while level: match, pos = matchorfail(sformat, pos)", "target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix)", "self.values()]) except (ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str())", "reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s", "\"INSERT INTO %s \" % tablename + q(_keys) + '", "SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\")", "<sql: \"SELECT * FROM test WHERE name='joe'\"> >>> q.query() 'SELECT", "AND y IN (2, 3)\"> \"\"\" if isinstance(a, list): return", "if svars is None: svars = {} where = self._where(where,", "def __str__(self): return \"unfinished expression in %s at char %d\"", "sformat[pos] == \".\" and \\ pos + 1 < len(sformat)", "INTO person (name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\"", "% ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery.", "= 'DELETE FROM ' + table if using: q +=", "`limit`, and `offset`. Uses vars to interpolate. Otherwise, each clause", "items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures", "q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql:", "isinstance(val, (int, long)): if sql == 'WHERE': nout = 'id", "< len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND", ">>> q <sql: \"SELECT * FROM test WHERE name='joe'\"> >>>", "IN (2, 3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else:", "* FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__", "if paramstyle in ['format', 'pyformat']: if '%' in x and", "tuple): # for some databases, a separate query has to", "sql query. >>> q = SQLQuery([\"SELECT * FROM test WHERE", "dollar + 1 + (nextchar == \"$\") if pos <", "== \"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks", "**values): \"\"\" Update `tables` with clause `where` (interpolated using `vars`)", "$name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name =", "list): self.items = items elif isinstance(items, SQLParam): self.items = [items]", "= sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try:", "(int, long)): if sql == 'WHERE': nout = 'id =", "1])) pos = dollar + 1 + (nextchar == \"$\")", "SQLParam(1)]) >>> q <sql: 'SELECT * FROM test WHERE x=1'>", "long)): where = \"id = \" + sqlparam(where) elif isinstance(where,", "into `tablename`. The `values` must be a list of dictioanries,", "select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False):", "foo.bar_id = bar.id LIMIT 5'> \"\"\" if svars is None:", "= [\"value\"] def __init__(self, value): self.value = value def get_marker(self,", "obj.decode(encoding) elif t in [int, float, bool]: return unicode(obj) elif", "svars) q = 'DELETE FROM ' + table if using:", "# For backward compatability, ignore escaping when the query looks", "be inserted, each with the same set of keys. Returns", "data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES ' %", "v in values: if v.keys() != keys: raise ValueError, 'Bad", "isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items =", "an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql:", "is None: self.items = [] elif isinstance(items, list): self.items =", "t is unicode: return obj elif t is str: return", "0: break nextchar = sformat[dollar + 1] if nextchar ==", "(ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self):", "{}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>>", "\\ pos + 1 < len(sformat) and sformat[pos + 1]", "pos + 1) elif sformat[pos] in \"([\": pos, level =", "VALUES\" % table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\"", "_test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not", "return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\"", "of dictioanries, one for each row to be inserted, each", "else: nout = SQLQuery(val) elif isinstance(val, (list, tuple)) and len(val)", "1] in namechars: match, pos = matchorfail(sformat, pos + 1)", "encoding='utf-8'): r\"\"\" Converts any given object to utf-8 encoded string.", "{}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>>", "__add__(self, other): return self.sqlquery() + other def __radd__(self, other): return", "of creating a new SQLQuery. \"\"\" if target is None:", ">>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode):", "self.ctx.commit() return out def update(self, tables, where, svars=None, _test=False, **values):", "sure all keys are valid # make sure all rows", "type(obj) if t is unicode: return obj elif t is", "can pass a dictionary to the keyword argument `vars` and", "part of the sql query. >>> q = SQLQuery([\"SELECT *", "db = DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True)", "is provided, the items are appended to target instead of", "databases, a separate query has to be made to find", "where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>>", "= %s, created = NOW() WHERE name = %s' >>>", "new SQLQuery. \"\"\" if target is None: target = SQLQuery()", "(basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented", "v): self.v = v def __repr__(self): return self.v class SQLProducer:", "sql_query = \"INSERT INTO %s \" % tablename + q(_keys)", "Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a,", "\" + where) if _test: return query db_cursor = self._db_cursor()", "items = [other] else: return NotImplemented return SQLQuery(items + self.items)", "other): return self.sqlquery() + other def __radd__(self, other): return other", "\"\"\" Selects `what` from `tables` with clauses `where`, `order`, `group`,", "__init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'): if paramstyle", "in enumerate(items): if i != 0: target_items.append(sep) if isinstance(item, SQLQuery):", "be a list of dictioanries, one for each row to", "= {} sql_clauses = self.sql_clauses(what, tables, where, group, order, limit,", "self.items = list(items.items) else: self.items = [items] # Take care", "return db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False): \"\"\"", "= 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's", "dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1,", "__str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return", "sformat[tstart:tend] if token == \"{\": level = level + 1", "_ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";", "SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.values() ['joe']", "sql_clauses(self, what, tables, where, group, order, limit, offset): return (", "for k in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if", "`where`, `order`, `group`, `limit`, and `offset`. Uses vars to interpolate.", "\"\"\" Takes a format string and returns a list of", "WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM test", "items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery):", "we have to do this the hard way... if obj", "pass a dictionary to the keyword argument `vars` and the", "sformat[pos:dollar])) pos, level = dollar + 2, 1 while level:", "`reparam`-style list to use instead of interpolating. >>> db =", "def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple", "row in enumerate(values): if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k])", "name = 'Joseph' >>> q = db.update('foo', where='name = $name',", "`tables` with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses", "backwards-compatibility elif isinstance(val, SQLQuery): nout = val else: nout =", "q <sql: \"INSERT INTO foo (age, name, created) VALUES (2,", "if target is None: target = SQLQuery() target_items = target.items", "and the function will call reparam for you. Internally, consists", "+ 1])) pos = dollar + 1 + (nextchar ==", "'WHERE x = ' + sqlquote(True) + ' AND y", "target_items = target.items if prefix: target_items.append(prefix) for i, item in", "safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return", "self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other) elif", "not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None,", "t in [int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__')", "return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj)", "a dictionary and interpolates the string using values from the", "query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using dictionary", "x = ' + sqlquote(True) + ' AND y IN", "(list, tuple)) and len(where) == 2: where = SQLQuery(where[0], where[1])", "\"\"\" return SQLQuery.join([k + ' = ' + sqlparam(v) for", "(tablename, ', '.join(keys))) for i, row in enumerate(values): if i", "tstart, tend = match.regs[3] token = sformat[tstart:tend] if token[0] in", "# we have to do this the hard way... if", "the list of ids of the inserted rows. Set `seqname`", "= {} where = self._where(where, svars) q = 'DELETE FROM", "def sqlquote(a): \"\"\" Ensures `a` is quoted properly for use", "else: return NotImplemented return SQLQuery(items + self.items) def __iadd__(self, other):", "__add__(self, other): if isinstance(other, basestring): items = [other] elif isinstance(other,", "= [other] elif isinstance(other, SQLQuery): items = other.items else: return", "creating a new SQLQuery. \"\"\" if target is None: target", "processed=True) def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values`", "sqlquery(self): return SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other", ">>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM", "unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any", "or paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle", "2, 3)'> \"\"\" items = [] items.append('(') for i, v", "s.append(safestr(x)) else: x = safestr(x) # automatically escape % characters", "is False: return None else: return out keys = values[0].keys()", "q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value): self.value", "if _test: return qout return self.query(qout, processed=True) def insert(self, tablename,", "values[0].keys() #@@ make sure all keys are valid # make", "is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query,", "pos < len(sformat): if sformat[pos] == \".\" and \\ pos", "return repr(obj) def sqllist(lst): \"\"\" Converts the arguments for use", "(age, name, created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT", "FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM", "WHERE \" + where) if _test: return query db_cursor =", "tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError): return self.query()", "True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\",", "self.sqlquery() + other def __radd__(self, other): return other + self.sqlquery()", "isinstance(other, SQLQuery): items = other.items else: return NotImplemented return SQLQuery(self.items", "what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what`", "self.items[i] = item.value.v def append(self, value): self.items.append(value) def __add__(self, other):", "unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4')", "If `processed=True`, `vars` is a `reparam`-style list to use instead", "elif isinstance(where, (list, tuple)) and len(where) == 2: where =", "sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self,", "= 'bob', created = NOW() WHERE name = 'Joseph'\"> >>>", "of the parameters used in the sql query. >>> q", "v in values.values()], ', ') sql_query = \"INSERT INTO %s", "rows. Set `seqname` to the ID if it's not the", "obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else:", "== 'numeric': return ':1' elif paramstyle is None or paramstyle", "* FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE x", "db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT *", "list(items.items) else: self.items = [items] # Take care of SQLLiterals", "== True and hash(1) == hash(True)` # we have to", "item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i]", "'<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return [] if", "db.query(\"SELECT * FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True)", "bar.id LIMIT 5'> \"\"\" if svars is None: svars =", "self def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns", "<sql: 'SELECT * FROM test WHERE x=1'> >>> q.query(), q.values()", "isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return target", "in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else:", "name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET age =", "= matchorfail(sformat, pos) tstart, tend = match.regs[3] token = sformat[tstart:tend]", "isinstance(val, SQLQuery): nout = val else: nout = reparam(val, svars)", "`tables` with clause `where` (interpolated using `vars`) and setting `values`.", "\" + sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) ==", "other): if isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery):", "match = tokenprog.match(text, pos) if match is None: raise _ItplError(text,", "paramstyle='pyformat'): if paramstyle == 'qmark': return '?' elif paramstyle ==", "itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\" converts `obj`", "sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND b =", "elif paramstyle is None or paramstyle in ['format', 'pyformat']: return", "a WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a')", "isinstance(where, (list, tuple)) and len(where) == 2: where = SQLQuery(where[0],", "sqllist(using) if where: q += ' WHERE ' + where", "\"\"\" raised for unsupported db paramstyles (currently supported: qmark, numeric,", "0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\"", "__init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'>", "hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj)", "== 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val,", "not the default, or to `False` if there isn't one.", "use in a SQL query. >>> 'WHERE x = '", "WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id =", "limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where),", "set of keys. Returns the list of ids of the", "= SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.values()", "text self.pos = pos def __str__(self): return \"unfinished expression in", "q.query() 'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT", "def insert(self, tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into", "if match is None: raise _ItplError(text, pos) return match, match.end()", "str(obj) def sqlify(obj): \"\"\" converts `obj` to its proper SQL", "call reparam for you. Internally, consists of `items`, which is", "`seqname` to the ID if it's not the default, or", "return \"unfinished expression in %s at char %d\" % (", "elif t in [int, float, bool]: return unicode(obj) elif hasattr(obj,", "DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'>", "svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects", "%s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is", "None: svars = {} sql_clauses = self.sql_clauses(what, tables, where, group,", "b'> Optinally, prefix and suffix arguments can be provided. >>>", "reparam for you. Internally, consists of `items`, which is a", "= $s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN", "level + 1 elif token == \"}\": level = level", "SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally, prefix and", "\"\"\" def __init__(self, v): self.v = v def __repr__(self): return", "delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes from `table`", "pass this sort of thing as a clause in any", "<sql: \"UPDATE foo SET age = 2, name = 'bob',", "2:pos - 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match,", "and returns a list of 2-tuples of the form (boolean,", "* FROM foo WHERE x = 'f'\"> \"\"\" if svars", "return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database.", "from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'>", "'SELECT * FROM test WHERE name=?' \"\"\" s = []", "= [] elif isinstance(items, list): self.items = items elif isinstance(items,", "be made to find # the id of the inserted", "x = 't' AND y = 3\"> >>> 'WHERE x", "return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a", "db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT * FROM foo'>", "(list, tuple)) and len(val) == 2: nout = SQLQuery(val[0], val[1])", "(name, email) VALUES ('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not", "q(x): return \"(\" + x + \")\" if values: _keys", "Yee) \"\"\" from tokenize import tokenprog tokenprog = tokenprog def", "__unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self))", "$x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE x", "sqllist(lst): \"\"\" Converts the arguments for use in something like", "foo (age, name, created) VALUES (2, 'bob', NOW())\"> >>> q.query()", "_sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2, 3)'>", "target_items.append(item) if suffix: target_items.append(suffix) return target join = staticmethod(join) def", "BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def", "x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM test WHERE", "Returns current sequence ID. Set `seqname` to the ID if", "self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where, svars=None, _test=False,", "def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows", "foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql:", "db.query(\"SELECT * FROM foo WHERE x = \" + sqlquote('f'),", "'WHERE': nout = 'id = ' + sqlquote(val) else: nout", "IN ' + sqlquote([2, 3]) <sql: \"WHERE x = 't'", "'.join(keys))) for i, row in enumerate(values): if i != 0:", "raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other):", "query part of the sql query. >>> q = SQLQuery([\"SELECT", "{}) >>> db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\",", "to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>>", "= DB(None, {}) >>> name = 'Joseph' >>> q =", "sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT", "return self.query() def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str())", "[other] elif isinstance(other, SQLQuery): items = other.items else: return NotImplemented", "values, seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`. The", "<sql: 'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id", "SQLQuery): nout = val else: nout = reparam(val, svars) def", "group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for", "%s' \"\"\" return SQLQuery.join([k + ' = ' + sqlparam(v)", "and suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'], ',", "SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return", "list of strings and SQLParams, which get concatenated to produce", "result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised", "SQLQuery(val[0], val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout = val", "= DB(None, {}) >>> db.select('foo', _test=True) <sql: 'SELECT * FROM", "b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst,", "WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM test WHERE", "order, limit, offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE',", "a `dictionary` to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id':", "else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format string", "token[0] in \"([\": level = level + 1 elif token[0]", "self.text = text self.pos = pos def __str__(self): return \"unfinished", "'bob', 'Joseph'] \"\"\" if svars is None: svars = {}", "The `values` must be a list of dictioanries, one for", "self.v = v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\"", "sqlquote(True) + ' AND y = ' + sqlquote(3) <sql:", "of the form (boolean, string) where boolean says whether string", "= 'id = ' + sqlquote(val) else: nout = SQLQuery(val)", "\" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM foo WHERE", "# automatically escape % characters in the query # For", "supported: qmark, numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def", "_sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes a format", "elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return", "gen_clause(self, sql, val, svars): if isinstance(val, (int, long)): if sql", "\"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\"", "self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None, svars=None,", "paramstyle == 'qmark': return '?' elif paramstyle == 'numeric': return", "db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out = None", "DB(None, {}) >>> name = 'Joe' >>> db.delete('foo', where='name =", "actual query. \"\"\" __slots__ = [\"items\"] # tested in sqlquote's", "!= keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO", "`group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise, each", "concatenated to produce the actual query. \"\"\" __slots__ = [\"items\"]", "return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted properly", "is str: return obj.decode(encoding) elif t in [int, float, bool]:", "each row to be inserted, each with the same set", "chunks.append((0, sformat[pos:dollar + 1])) pos = dollar + 1 +", "SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'> If", "val else: nout = reparam(val, svars) def xjoin(a, b): if", "= SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for v in", "self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1)", "return str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam", "qout = SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True)", "SQLQuery(object): \"\"\" You can pass this sort of thing as", "WHERE name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test", "Deletes from `table` with clauses `where` and `using`. >>> db", "a clause in any db function. Otherwise, you can pass", "SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted properly for", "repr(obj) def sqllist(lst): \"\"\" Converts the arguments for use in", "if obj is None: return 'NULL' elif obj is True:", "offset=None, _test=False): \"\"\" Selects `what` from `tables` with clauses `where`,", "!= 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\",", "lan (www.9miao.com) ''' import itertools import datetime def safeunicode(obj, encoding='utf-8'):", "in namechars: match, pos = matchorfail(sformat, pos + 1) elif", "enumerate(values): if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return", "suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ',", "\" % tablename + q(_keys) + ' VALUES ' +", "sql_query = SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename,", "+ self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)): self.items.append(other)", "len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query part of", "def sqllist(lst): \"\"\" Converts the arguments for use in something", "i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys],", "Converts any given object to utf-8 encoded string. >>> safestr('hello')", "= 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s", "v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a", "y = ' + sqlquote(3) <sql: \"WHERE x = 't'", "('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset))", "% tuple([sqlify(x) for x in self.values()]) except (ValueError, TypeError): return", ">>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring):", "= 3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3},", "find # the id of the inserted row. q1, q2", "= db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT", "offset): return ( ('SELECT', what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP", "SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self): return", "sql_clauses if val is not None] qout = SQLQuery.join(clauses) if", "to produce the actual query. \"\"\" __slots__ = [\"items\"] #", "\"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql:", "\")]\": level = level - 1 else: break chunks.append((1, sformat[dollar", "made to find # the id of the inserted row.", "level = pos + 1, 1 while level: match, pos", "sql_query db_cursor = self._db_cursor() if seqname is not False: sql_query", "* FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT *", "sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) == 2: where", "def update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update `tables`", "= 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x =", "q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query)", "i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def", "return '?' elif paramstyle == 'numeric': return ':1' elif paramstyle", "obj is True: return \"'t'\" elif obj is False: return", "sqlquote([2, 3]) <sql: \"WHERE x = 't' AND y IN", "it. If `processed=True`, `vars` is a `reparam`-style list to use", "1, 1 while level: match, pos = matchorfail(sformat, pos) tstart,", "self._db_cursor() if seqname is not False: sql_query = self._process_insert_query(sql_query, tablename,", "sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT',", "i, item in enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral):", "string and a dictionary and interpolates the string using values", "= SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where =", "object to utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234')", "is None: return 'NULL' elif obj is True: return \"'t'\"", "\"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos = 0 while", "result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s = 't'\">", "def _interpolate(sformat): \"\"\" Takes a format string and returns a", "eval mucks with it result = [] for live, chunk", "return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db", "seqname is False: return None else: return out keys =", "{} where = self._where(where, svars) q = 'DELETE FROM '", "= 3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query()", "' WHERE ' + where return q sqlproducer = SQLProducer()", "__repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects", "in the sql query. >>> q = SQLQuery([\"SELECT * FROM", "sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst else: return", "\"UPDATE foo SET age = 2, name = 'bob', created", "a string and a dictionary and interpolates the string using", "<sql: \"INSERT INTO foo (age, name, created) VALUES (2, 'bob',", "keys. Returns the list of ids of the inserted rows.", "the same set of keys. Returns the list of ids", "items = other.items else: return NotImplemented return SQLQuery(self.items + items)", ">>> db.select('foo', _test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo',", "= db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(),", "a separate query has to be made to find #", "* FROM foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql:", "__slots__ = [\"items\"] # tested in sqlquote's docstring def __init__(self,", "nout = reparam(val, svars) def xjoin(a, b): if a and", "values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v) for", "= [] items.append('(') for i, v in enumerate(values): if i", "\"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if", "('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val, svars): if", "values: if v.keys() != keys: raise ValueError, 'Bad data' sql_query", "numeric, format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text,", "db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name, email) VALUES", "utf-8 encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>>", "in something like a WHERE clause. >>> sqllist(['a', 'b']) 'a,", "' + sqlquote(True) + ' AND y = ' +", "k, v in dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes", "' + table if using: q += ' USING '", "return 'NULL' elif obj is True: return \"'t'\" elif obj", "token[0] in \")]\": level = level - 1 else: break", "\"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2, 1", "1: dollar = sformat.find(\"$\", pos) if dollar < 0: break", "3)\"> \"\"\" if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery()", "self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self,", "svars is None: svars = {} if not processed and", "\"{\": level = level + 1 elif token == \"}\":", "valid # make sure all rows have same keys. for", "test WHERE x=1'> >>> q.query(), q.values() ('SELECT * FROM test", "db = DB(None, {}) >>> db.supports_multiple_insert = True >>> values", "len(sformat): if sformat[pos] == \".\" and \\ pos + 1", "x.replace('%', '%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the", "each clause can be a SQLQuery. >>> db = DB(None,", "items.append('(') for i, v in enumerate(values): if i != 0:", "not in x: x = x.replace('%', '%%') s.append(x) return \"\".join(s)", "1) elif sformat[pos] in \"([\": pos, level = pos +", "sformat[pos] in \"([\": pos, level = pos + 1, 1", "[] items.append('(') for i, v in enumerate(values): if i !=", "or b return xjoin(sql, nout) def _where(self, where, svars): if", "= DB(None, {}) >>> db.query(\"SELECT * FROM foo\", _test=True) <sql:", "= SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>> q", "get concatenated to produce the actual query. \"\"\" __slots__ =", "isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self,", "in [int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or", "def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' %", "string) where boolean says whether string should be evaled or", "\"\"\" if svars is None: svars = {} where =", "sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return", "= \"INSERT INTO %s \" % tablename + q(_keys) +", "q.query(), q.values() ('SELECT * FROM test WHERE x=%s', [1]) >>>", "sqllist(tables) + \" SET \" + sqlwhere(values, ', ') +", "5'> \"\"\" if svars is None: svars = {} sql_clauses", "def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates", "+ q(_keys) + ' VALUES ' + q(_values) else: sql_query", "self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out =", "'a, b'> Optinally, prefix and suffix arguments can be provided.", "i, v in enumerate(values): if i != 0: items.append(', ')", "\"'t'\" >>> sqlify(3) '3' \"\"\" # because `1 == True", "= level - 1 else: break chunks.append((1, sformat[dollar + 1:pos]))", "items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is quoted", "self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0] out", "order=None, group=None, limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables`", "db_cursor = self._db_cursor() if seqname is not False: sql_query =", "if isinstance(a, list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat):", "prefix='(', suffix=')') <sql: '(a, b)'> If target argument is provided,", "function. Otherwise, you can pass a dictionary to the keyword", "'2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str):", "return sql_query db_cursor = self._db_cursor() if seqname is not False:", "import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any", "__slots__ = [\"value\"] def __init__(self, value): self.value = value def", "'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE", "class SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass", "SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other def __radd__(self,", "_test=True) <sql: 'SELECT * FROM foo, bar WHERE foo.bar_id =", "NOW())\"> >>> q.query() 'INSERT INTO foo (age, name, created) VALUES", "1 else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar", "= {} if not processed and not isinstance(sql_query, SQLQuery): sql_query", "where: q += ' WHERE ' + where return q", "1) while pos < len(sformat): if sformat[pos] == \".\" and", "* FROM foo WHERE x = 'f'\"> >>> db.query(\"SELECT *", "thing as a clause in any db function. Otherwise, you", "target.items if prefix: target_items.append(prefix) for i, item in enumerate(items): if", "using values from the dictionary. Returns an `SQLQuery` for the", "else: self.items = [items] # Take care of SQLLiterals for", "tuple)) and len(where) == 2: where = SQLQuery(where[0], where[1]) elif", "to find # the id of the inserted row. q1,", "'b'], ', ', prefix='(', suffix=')') <sql: '(a, b)'> If target", "INTO %s (%s) VALUES ' % (tablename, ', '.join(keys))) for", "Returns an `SQLQuery` for the result. >>> reparam(\"s = $s\",", "database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL", "< len(sformat) and sformat[pos + 1] in namechars: match, pos", "'b'], ', ') <sql: 'a, b'> Optinally, prefix and suffix", "level = level - 1 else: break chunks.append((1, sformat[dollar +", "'<EMAIL>')\"> \"\"\" if not values: return [] if not self.supports_multiple_insert:", "Returns the values of the parameters used in the sql", "_test=True) <sql: \"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\"", "`SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND", "out = None if not self.ctx.transactions: self.ctx.commit() return out def", "is True: return \"'t'\" elif obj is False: return \"'f'\"", "else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar + 1", "isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery): items =", "'id = ' + sqlquote(val) else: nout = SQLQuery(val) elif", "in x: x = x.replace('%', '%%') s.append(x) return \"\".join(s) def", ">>> q.query() 'UPDATE foo SET age = %s, name =", "sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>>", "\"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person', values=values,", "= type(obj) if t is unicode: return obj elif t", "\"'t'\" elif obj is False: return \"'f'\" elif datetime and", "def _sqllist(values): \"\"\" >>> _sqllist([1, 2, 3]) <sql: '(1, 2,", "value def get_marker(self, paramstyle='pyformat'): if paramstyle == 'qmark': return '?'", "where def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None,", "\"WHERE x = 't' AND y IN (2, 3)\"> \"\"\"", "tables, where, group, order, limit, offset) clauses = [self.gen_clause(sql, val,", "items are appended to target instead of creating a new", "pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query`", "is None: target = SQLQuery() target_items = target.items if prefix:", "result = [] for live, chunk in _interpolate(string_): if live:", "of ids of the inserted rows. Set `seqname` to the", "match, pos = matchorfail(sformat, pos) tstart, tend = match.regs[3] token", "return lst else: return ', '.join(lst) def _sqllist(values): \"\"\" >>>", "nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar", "'s IN (1, 2)'> \"\"\" dictionary = dictionary.copy() # eval", "argument is provided, the items are appended to target instead", "tablename, seqname=None, _test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns", "in keys], sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return", "test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE", "isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def __len__(self):", "or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from", "text, pos): ValueError.__init__(self) self.text = text self.pos = pos def", "USING ' + sqllist(using) if where: q += ' WHERE", "return [i.value for i in self.items if isinstance(i, SQLParam)] def", "a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute", "= \"id = \" + sqlparam(where) elif isinstance(where, (list, tuple))", "multiple queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'>", "if sformat[pos] == \".\" and \\ pos + 1 <", "a and b: return a + ' ' + b", "return safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self)) class", "nout = val else: nout = reparam(val, svars) def xjoin(a,", "@author: lan (www.9miao.com) ''' import itertools import datetime def safeunicode(obj,", "elif obj is False: return \"'f'\" elif datetime and isinstance(obj,", "t = type(obj) if t is unicode: return obj elif", "paramstyle in ['format', 'pyformat']: if '%' in x and '%%'", "WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET age", "1 elif token == \"}\": level = level - 1", "('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY', order),", "with clauses `where`, `order`, `group`, `limit`, and `offset`. Uses vars", "repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q", "foo, bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\" if", "', ') sql_query = \"INSERT INTO %s \" % tablename", "Exception: out = None if not self.ctx.transactions: self.ctx.commit() return out", "SET age = 2, name = 'bob', created = NOW()", "DEFAULT VALUES\" % table def multiple_insert(self, tablename, values, seqname=None, _test=False):", "the query looks already escaped if paramstyle in ['format', 'pyformat']:", "'') class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently", "hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding)", "some databases, a separate query has to be made to", "sql, val, svars): if isinstance(val, (int, long)): if sql ==", "evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\"", "basestring): items = [other] elif isinstance(other, SQLQuery): items = other.items", "interpolate. Otherwise, each clause can be a SQLQuery. >>> db", "def sqlify(obj): \"\"\" converts `obj` to its proper SQL version", "a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()'))", "else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return", "None if not self.ctx.transactions: self.ctx.commit() return out def update(self, tables,", "Converts the arguments for use in something like a WHERE", "svars=None, _test=False, **values): \"\"\" Update `tables` with clause `where` (interpolated", "if token[0] in \"([\": level = level + 1 elif", "x = ' + sqlquote(True) + ' AND y =", "\"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass def query(self,", "= ' + sqlparam(v) for k, v in dictionary.items()], grouping)", "break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1]))", "into `tablename`. Returns current sequence ID. Set `seqname` to the", "return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks =", "svars) return sql_query def sql_clauses(self, what, tables, where, group, order,", "if seqname is False: return None else: return out keys", "else: x = safestr(x) # automatically escape % characters in", "converts `obj` to its proper SQL version >>> sqlify(None) 'NULL'", "Takes a format string and returns a list of 2-tuples", "== 'qmark': return '?' elif paramstyle == 'numeric': return ':1'", "'%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self,", "[i.value for i in self.items if isinstance(i, SQLParam)] def join(items,", "items = [] items.append('(') for i, v in enumerate(values): if", "limit=5, _test=True) <sql: 'SELECT * FROM foo, bar WHERE foo.bar_id", "the query part of the sql query. >>> q =", "where = self._where(where, svars) q = 'DELETE FROM ' +", "\", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor =", "pos, level = pos + 1, 1 while level: match,", "query = ( \"UPDATE \" + sqllist(tables) + \" SET", "unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\"", "Execute SQL query `sql_query` using dictionary `vars` to interpolate it.", "test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE", "1 + (nextchar == \"$\") if pos < len(sformat): chunks.append((0,", "+= ' USING ' + sqllist(using) if where: q +=", "use in something like a WHERE clause. >>> sqllist(['a', 'b'])", "enumerate(items): if i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items)", "if isinstance(other, basestring): items = [other] elif isinstance(other, SQLQuery): items", "1 while level: match, pos = matchorfail(sformat, pos) tstart, tend", "val is not None] qout = SQLQuery.join(clauses) if _test: return", "[self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if seqname", "'INSERT INTO foo (age, name, created) VALUES (%s, %s, NOW())'", "else: break chunks.append((1, sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar +", "if val is not None] qout = SQLQuery.join(clauses) if _test:", "def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to utf-8", "to the keyword argument `vars` and the function will call", "x = 'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x", "self.pos = pos def __str__(self): return \"unfinished expression in %s", "class UnknownParamstyle(Exception): \"\"\" raised for unsupported db paramstyles (currently supported:", "isinstance(where, SQLQuery): pass else: where = reparam(where, svars) return where", "len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '):", "with clause `where` (interpolated using `vars`) and setting `values`. >>>", "* FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT *", "tables, where, svars=None, _test=False, **values): \"\"\" Update `tables` with clause", "if values: _keys = SQLQuery.join(values.keys(), ', ') _values = SQLQuery.join([sqlparam(v)", "in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else:", "'%' in x and '%%' not in x: x =", "paramstyle=None): \"\"\" Returns the query part of the sql query.", "name=\", SQLParam('joe')]) >>> q.values() ['joe'] \"\"\" return [i.value for i", "something like a WHERE clause. >>> sqllist(['a', 'b']) 'a, b'", "+ x + \")\" if values: _keys = SQLQuery.join(values.keys(), ',", "+ ' = ' + sqlparam(v) for k, v in", "to do this the hard way... if obj is None:", "name = 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True)", "paramstyle is None or paramstyle in ['format', 'pyformat']: return '%s'", "db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes", "'pyformat']: if '%' in x and '%%' not in x:", "\"\"\" Deletes from `table` with clauses `where` and `using`. >>>", "target_items.append(prefix) for i, item in enumerate(items): if i != 0:", "order, limit, offset) clauses = [self.gen_clause(sql, val, svars) for sql,", "\"$\") if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def", "matchorfail(sformat, dollar + 1) while pos < len(sformat): if sformat[pos]", "if isinstance(where, (int, long)): where = \"id = \" +", "SQLQuery('INSERT INTO %s (%s) VALUES ' % (tablename, ', '.join(keys)))", "2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id =", "x in self.values()]) except (ValueError, TypeError): return self.query() def __str__(self):", "created) VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\"", "if isinstance(other, basestring): items = [other] else: return NotImplemented return", "isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\"", "sep=\", \", target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor", "elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr, obj) else: return", "class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT", "in sql_clauses if val is not None] qout = SQLQuery.join(clauses)", ">>> name = 'Joseph' >>> q = db.update('foo', where='name =", "$name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql:", "if pos < len(sformat): chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary,", "the function will call reparam for you. Internally, consists of", "\"\"\" Returns the query part of the sql query. >>>", "\"INSERT INTO foo (age, name, created) VALUES (2, 'bob', NOW())\">", "+ sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list, tuple))", "_test=False): \"\"\" Selects `what` from `tables` with clauses `where`, `order`,", "values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}]", ">>> db.query(\"SELECT * FROM foo\", _test=True) <sql: 'SELECT * FROM", "sqlparam(v) for k, v in dictionary.items()], grouping) def reparam(string_, dictionary):", ">>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a = %s AND b", "other def __radd__(self, other): return other + self.sqlquery() def __str__(self):", "= $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE", "query. >>> q = SQLQuery([\"SELECT * FROM test WHERE name=\",", "None: raise _ItplError(text, pos) return match, match.end() namechars = \"abcdefghijklmnopqrstuvwxyz\"", "' AND y = ' + sqlquote(3) <sql: \"WHERE x", "and \\ pos + 1 < len(sformat) and sformat[pos +", "_test=True) >>> q <sql: \"UPDATE foo SET age = 2,", "nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level = dollar +", "Selects `what` from `tables` with clauses `where`, `order`, `group`, `limit`,", "(%s, %s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x):", "= matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\": pos,", "SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT *", "pos): match = tokenprog.match(text, pos) if match is None: raise", "'t'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN", "reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables, where, group,", "return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj)", "encoded string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2)", "elif isinstance(val, SQLQuery): nout = val else: nout = reparam(val,", "a new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q =", "else: return str(obj) def sqlify(obj): \"\"\" converts `obj` to its", "return [] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test,", "return other + self.sqlquery() def __str__(self): return str(self.value) def __repr__(self):", "lst else: return ', '.join(lst) def _sqllist(values): \"\"\" >>> _sqllist([1,", "self._where(where, svars) query = ( \"UPDATE \" + sqllist(tables) +", "return SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other, basestring):", "('OFFSET', offset)) def gen_clause(self, sql, val, svars): if isinstance(val, (int,", "== \".\" and \\ pos + 1 < len(sformat) and", "Converts a `dictionary` to an SQL WHERE clause `SQLQuery`. >>>", "NotImplemented return self def __len__(self): return len(self.query()) def query(self, paramstyle=None):", "'order_id':3}) <sql: 'order_id = 3 AND cust_id = 2'> >>>", "tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None, _test=False): \"\"\"", "raised for unsupported db paramstyles (currently supported: qmark, numeric, format,", "or to `False` if there isn't one. >>> db =", "_values = SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query", "class SQLLiteral: \"\"\" Protects a string from `sqlquote`. >>> sqlquote('NOW()')", "x = x.get_marker(paramstyle) s.append(safestr(x)) else: x = safestr(x) # automatically", "db = DB(None, {}) >>> name = 'Joseph' >>> q", "if i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else:", "of `items`, which is a list of strings and SQLParams,", "chunks = [] pos = 0 while 1: dollar =", "FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM", "in x and '%%' not in x: x = x.replace('%',", "sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>>", "') <sql: 'order_id = 3, cust_id = 2'> >>> sqlwhere({'a':", "2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id =", ">>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj)", "\"DELETE FROM foo WHERE name = 'Joe'\"> \"\"\" if svars", "sqlparam = SQLParam class SQLQuery(object): \"\"\" You can pass this", "'SELECT * FROM test WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT *", "row to be inserted, each with the same set of", "= level + 1 elif token == \"}\": level =", "prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a', 'b'],", "$s\", dict(s=[1, 2])) <sql: 's IN (1, 2)'> \"\"\" dictionary", "') <sql: 'a, b'> Optinally, prefix and suffix arguments can", "sqlquote(True) + ' AND y IN ' + sqlquote([2, 3])", "0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \",", "not processed and not isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars)", "* FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5,", "q.values() ['joe'] \"\"\" return [i.value for i in self.items if", "name=\", SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test WHERE", "= eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class", "Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog = tokenprog", "\"\"\" __slots__ = [\"items\"] # tested in sqlquote's docstring def", "SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q = SQLQuery([\"SELECT *", "a list of 2-tuples of the form (boolean, string) where", "(www.9miao.com) ''' import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\"", "and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj", "using: q += ' USING ' + sqllist(using) if where:", "\"\"\" pass def query(self, sql_query,processed=False, svars=None): \"\"\" Execute SQL query", "out keys = values[0].keys() #@@ make sure all keys are", ">>> db = DB(None, {}) >>> q = db.insert('foo', name='bob',", "tablename, seqname) if isinstance(sql_query, tuple): # for some databases, a", "sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc'", "if t is unicode: return obj elif t is str:", "do this the hard way... if obj is None: return", "$s\", dict(s=True)) <sql: \"s = 't'\"> >>> reparam(\"s IN $s\",", "the id of the inserted row. q1, q2 = sql_query", "None: svars = {} where = self._where(where, svars) q =", "[int, float, bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj,", "<sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT * FROM foo", "name='joe'\"> >>> q.query() 'SELECT * FROM test WHERE name=%s' >>>", "_test=False): \"\"\" Deletes from `table` with clauses `where` and `using`.", "%d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter in", "else: if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj) def", "ID if it's not the default, or to `False` if", "sformat[dollar + 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos =", "in any db function. Otherwise, you can pass a dictionary", "<sql: \"SELECT * FROM foo WHERE x = 'f'\"> \"\"\"", "x and '%%' not in x: x = x.replace('%', '%%')", "You can pass this sort of thing as a clause", "nextchar = sformat[dollar + 1] if nextchar == \"{\": chunks.append((0,", "WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM", "('WHERE', where), ('GROUP BY', group), ('ORDER BY', order), ('LIMIT', limit),", "join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries.", "%s (%s) VALUES ' % (tablename, ', '.join(keys))) for i,", "def __init__(self, value): self.value = value def get_marker(self, paramstyle='pyformat'): if", "in \"([\": pos, level = pos + 1, 1 while", "same keys. for v in values: if v.keys() != keys:", "isinstance(sql_query, SQLQuery): sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self,", "['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return", "all keys are valid # make sure all rows have", "char %d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\" Parameter", "= val else: nout = reparam(val, svars) def xjoin(a, b):", "\"\"\" Returns the values of the parameters used in the", "SQLParam class SQLQuery(object): \"\"\" You can pass this sort of", "if prefix: target_items.append(prefix) for i, item in enumerate(items): if i", "query. >>> 'WHERE x = ' + sqlquote(True) + '", "[items] # Take care of SQLLiterals for i, item in", "grouping=', ') <sql: 'order_id = 3, cust_id = 2'> >>>", "FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True)", "staticmethod(join) def _str(self): try: return self.query() % tuple([sqlify(x) for x", "WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE", "already escaped if paramstyle in ['format', 'pyformat']: if '%' in", ">>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally, prefix", "Inserts `values` into `tablename`. Returns current sequence ID. Set `seqname`", "for some databases, a separate query has to be made", "<sql: 'NOW()'> \"\"\" def __init__(self, v): self.v = v def", "namechars = \"abcdefghijklmnopqrstuvwxyz\" \\ \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"; chunks = [] pos =", "age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo (age,", "escaping when the query looks already escaped if paramstyle in", "None: self.items = [] elif isinstance(items, list): self.items = items", "isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\"", ">>> db.query(\"SELECT * FROM foo WHERE x = $x\", vars=dict(x='f'),", "('foo', '<EMAIL>'), ('bar', '<EMAIL>')\"> \"\"\" if not values: return []", "'(a, b)'> If target argument is provided, the items are", "', prefix=None, suffix=None, target=None): \"\"\" Joins multiple queries. >>> SQLQuery.join(['a',", "are appended to target instead of creating a new SQLQuery.", "def select(self, tables, svars=None, what='*', where=None, order=None, group=None, limit=None, offset=None,", "<sql: 'order_id = 3 AND cust_id = 2'> >>> sqlwhere({'cust_id':", "return ':1' elif paramstyle is None or paramstyle in ['format',", ">>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because `1", "+ sqlparam(v) for k, v in dictionary.items()], grouping) def reparam(string_,", "'%%') s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the values", "+ sqlquote(True) + ' AND y IN ' + sqlquote([2,", "foo WHERE name = 'Joe'\"> \"\"\" if svars is None:", "raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s)", "inserted row. q1, q2 = sql_query self._db_execute(db_cursor, q1) self._db_execute(db_cursor, q2)", "name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo", "table if using: q += ' USING ' + sqllist(using)", "+ \" WHERE \" + where) if _test: return query", "NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x): return \"(\"", "dictionary = dictionary.copy() # eval mucks with it result =", "else: return NotImplemented return SQLQuery(self.items + items) def __radd__(self, other):", "sqlify(3) '3' \"\"\" # because `1 == True and hash(1)", "Otherwise, you can pass a dictionary to the keyword argument", "val[1]) # backwards-compatibility elif isinstance(val, SQLQuery): nout = val else:", "encoding='utf-8'): r\"\"\" Converts any given object to unicode string. >>>", "!= 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if", "safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj,", "WHERE clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a'", "cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql:", "in values: if v.keys() != keys: raise ValueError, 'Bad data'", "vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name = 'Joe'\">", "\"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text", "% table def multiple_insert(self, tablename, values, seqname=None, _test=False): \"\"\" Inserts", "* FROM test WHERE name=?' \"\"\" s = [] for", "# Take care of SQLLiterals for i, item in enumerate(self.items):", "for unsupported db paramstyles (currently supported: qmark, numeric, format, pyformat)", "\"\"\" def q(x): return \"(\" + x + \")\" if", "if i != 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items)", "AND y = 3\"> >>> 'WHERE x = ' +", "created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO foo (age, name,", "level - 1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif", "self.items = [items] # Take care of SQLLiterals for i,", "name, created) VALUES (%s, %s, NOW())' >>> q.values() [2, 'bob']", "return SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other, (basestring,", "q <sql: \"UPDATE foo SET age = 2, name =", "sort of thing as a clause in any db function.", "return \"'t'\" elif obj is False: return \"'f'\" elif datetime", "= range(out-len(values)+1, out+1) except Exception: out = None if not", "def __init__(self, items=None): r\"\"\"Creates a new SQLQuery. >>> SQLQuery(\"x\") <sql:", "function will call reparam for you. Internally, consists of `items`,", "created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET age", ">>> db.select(['foo', 'bar'], where=\"foo.bar_id = bar.id\", limit=5, _test=True) <sql: 'SELECT", "in ['format', 'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self):", "b else: return a or b return xjoin(sql, nout) def", "_interpolate(sformat): \"\"\" Takes a format string and returns a list", "3 AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=',", "val, svars): if isinstance(val, (int, long)): if sql == 'WHERE':", "sqlify(obj): \"\"\" converts `obj` to its proper SQL version >>>", "') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a`", "and sformat[pos + 1] in namechars: match, pos = matchorfail(sformat,", "care of SQLLiterals for i, item in enumerate(self.items): if isinstance(item,", "FROM test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ =", "string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql:", "interpolate it. If `processed=True`, `vars` is a `reparam`-style list to", "reparam(val, svars) def xjoin(a, b): if a and b: return", "where) if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query)", "token = sformat[tstart:tend] if token == \"{\": level = level", "sql_clauses = self.sql_clauses(what, tables, where, group, order, limit, offset) clauses", "can pass this sort of thing as a clause in", "= SQLQuery() target_items = target.items if prefix: target_items.append(prefix) for i,", "dictionary `vars` to interpolate it. If `processed=True`, `vars` is a", "arguments for use in something like a WHERE clause. >>>", "= %s, name = %s, created = NOW() WHERE name", "chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary`", "' + sqlquote(val) else: nout = SQLQuery(val) elif isinstance(val, (list,", "- 1])) elif nextchar in namechars: chunks.append((0, sformat[pos:dollar])) match, pos", "string. >>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2'", "{}) >>> name = 'Joe' >>> db.delete('foo', where='name = $name',", "values of the parameters used in the sql query. >>>", "def __init__(self, text, pos): ValueError.__init__(self) self.text = text self.pos =", "DB(None, {}) >>> db.supports_multiple_insert = True >>> values = [{\"name\":", "safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to utf-8 encoded", "chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1) while", "which is a list of strings and SQLParams, which get", "`dictionary` to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2,", "other + self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return", "isinstance(other, (basestring, SQLParam)): self.items.append(other) elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return", "len(val) == 2: nout = SQLQuery(val[0], val[1]) # backwards-compatibility elif", "be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee)", "<reponame>handsome3163/H2Dgame-Firefly<gh_stars>100-1000 #coding:utf8 ''' Created on 2013-8-21 @author: lan (www.9miao.com) '''", "'SELECT * FROM test WHERE x=1'> >>> q.query(), q.values() ('SELECT", "item.value.v def append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other,", "+ sqlparam(where) elif isinstance(where, (list, tuple)) and len(where) == 2:", "elif token[0] in \")]\": level = level - 1 else:", "keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT INTO %s", "one. >>> db = DB(None, {}) >>> q = db.insert('foo',", "q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")]) >>>", "return self def __len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\"", "the dictionary. Returns an `SQLQuery` for the result. >>> reparam(\"s", "values(self): \"\"\" Returns the values of the parameters used in", "y = 3\"> >>> 'WHERE x = ' + sqlquote(True)", "BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql, val,", "SQLQuery.join(clauses) if _test: return qout return self.query(qout, processed=True) def insert(self,", "query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit()", "Created on 2013-8-21 @author: lan (www.9miao.com) ''' import itertools import", "', '.join(keys))) for i, row in enumerate(values): if i !=", "elif isinstance(items, SQLQuery): self.items = list(items.items) else: self.items = [items]", "from `table` with clauses `where` and `using`. >>> db =", "to target instead of creating a new SQLQuery. \"\"\" if", "v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '')", "def __init__(self, v): self.v = v def __repr__(self): return self.v", "what), ('FROM', sqllist(tables)), ('WHERE', where), ('GROUP BY', group), ('ORDER BY',", "FROM foo, bar WHERE foo.bar_id = bar.id LIMIT 5'> \"\"\"", "(age, name, created) VALUES (%s, %s, NOW())' >>> q.values() [2,", "__radd__(self, other): return other + self.sqlquery() def __str__(self): return str(self.value)", "foo WHERE x = 'f'\"> \"\"\" if svars is None:", "else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception): \"\"\" raised for", "0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix:", "make sure all rows have same keys. for v in", "WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def", "val in sql_clauses if val is not None] qout =", "datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to", "\"\"\" if svars is None: svars = {} sql_clauses =", "u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t =", "pos + 1 < len(sformat) and sformat[pos + 1] in", "db = DB(None, {}) >>> name = 'Joe' >>> db.delete('foo',", "self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x)) else: x", "string using values from the dictionary. Returns an `SQLQuery` for", "else: return out keys = values[0].keys() #@@ make sure all", "Protects a string from `sqlquote`. >>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>>", "`offset`. Uses vars to interpolate. Otherwise, each clause can be", "== \"}\": level = level - 1 chunks.append((1, sformat[dollar +", "_test=True) >>> q <sql: \"INSERT INTO foo (age, name, created)", "SQLParam)] def join(items, sep=' ', prefix=None, suffix=None, target=None): \"\"\" Joins", "SQLQuery.join([k + ' = ' + sqlparam(v) for k, v", "_str(self): try: return self.query() % tuple([sqlify(x) for x in self.values()])", "' + sqlquote([2, 3]) <sql: \"WHERE x = 't' AND", "AND y = ' + sqlquote(3) <sql: \"WHERE x =", "_test=False, **values): \"\"\" Inserts `values` into `tablename`. Returns current sequence", "basestring): items = [other] else: return NotImplemented return SQLQuery(items +", ">>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name, email)", "' = ' + sqlparam(v) for k, v in dictionary.items()],", "given object to unicode string. >>> safeunicode('hello') u'hello' >>> safeunicode(2)", "x = \" + sqlquote('f'), _test=True) <sql: \"SELECT * FROM", "' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def", "!= 0: items.append(', ') items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a):", "eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '') class UnknownParamstyle(Exception):", "self.sqlquery() def __str__(self): return str(self.value) def __repr__(self): return '<param: %s>'", "else: return a or b return xjoin(sql, nout) def _where(self,", "= NOW() WHERE name = %s' >>> q.values() [2, 'bob',", "namechars: match, pos = matchorfail(sformat, pos + 1) elif sformat[pos]", "_get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\" % table", "reparam(string_, dictionary): \"\"\" Takes a string and a dictionary and", "= match.regs[3] token = sformat[tstart:tend] if token == \"{\": level", "string should be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain,", "chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar in namechars:", "+ items) def __radd__(self, other): if isinstance(other, basestring): items =", "to use instead of interpolating. >>> db = DB(None, {})", "sql_query = reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables,", "svars) for sql, val in sql_clauses if val is not", "self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def", ">>> q.values() [2, 'bob'] \"\"\" def q(x): return \"(\" +", "UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self]) def __add__(self, other): return", "match is None: raise _ItplError(text, pos) return match, match.end() namechars", "and interpolates the string using values from the dictionary. Returns", "new SQLQuery. >>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT", "= [] pos = 0 while 1: dollar = sformat.find(\"$\",", "live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result,", "WHERE name=?' \"\"\" s = [] for x in self.items:", "return obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'):", "dollar < 0: break nextchar = sformat[dollar + 1] if", "FROM foo'> >>> db.query(\"SELECT * FROM foo WHERE x =", "{}) >>> name = 'Joseph' >>> q = db.update('foo', where='name", "= sformat[tstart:tend] if token[0] in \"([\": level = level +", "+ sqlquote(3) <sql: \"WHERE x = 't' AND y =", "offset)) def gen_clause(self, sql, val, svars): if isinstance(val, (int, long)):", "_test: return qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None,", "default, or to `False` if there isn't one. >>> db", "SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query = \"INSERT", "svars is None: svars = {} sql_clauses = self.sql_clauses(what, tables,", "chunks.append((0, sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\"", "if paramstyle == 'qmark': return '?' elif paramstyle == 'numeric':", "NotImplemented return SQLQuery(self.items + items) def __radd__(self, other): if isinstance(other,", "`vars` is a `reparam`-style list to use instead of interpolating.", "= self._db_cursor() if seqname is not False: sql_query = self._process_insert_query(sql_query,", ">>> db.supports_multiple_insert = True >>> values = [{\"name\": \"foo\", \"email\":", "return str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object", "'next'): # iterator return itertools.imap(safestr, obj) else: return str(obj) def", "x = 'f'\"> \"\"\" if svars is None: svars =", "properly for use in a SQL query. >>> 'WHERE x", "' + sqlparam(v) for k, v in dictionary.items()], grouping) def", "SQLParams, which get concatenated to produce the actual query. \"\"\"", "target join = staticmethod(join) def _str(self): try: return self.query() %", "with it result = [] for live, chunk in _interpolate(string_):", "items is None: self.items = [] elif isinstance(items, list): self.items", "pos + 1, 1 while level: match, pos = matchorfail(sformat,", "= item.value.v def append(self, value): self.items.append(value) def __add__(self, other): if", "def __str__(self): return safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self):", "x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle) s.append(safestr(x))", "clause. >>> sqllist(['a', 'b']) 'a, b' >>> sqllist('a') 'a' >>>", "' + sqlquote(True) + ' AND y IN ' +", "VALUES ' % (tablename, ', '.join(keys))) for i, row in", "ids of the inserted rows. Set `seqname` to the ID", "offset) clauses = [self.gen_clause(sql, val, svars) for sql, val in", "\"unfinished expression in %s at char %d\" % ( repr(self.text),", ">>> db.query(\"SELECT * FROM foo WHERE x = \" +", "'NULL' >>> sqlify(True) \"'t'\" >>> sqlify(3) '3' \"\"\" # because", "Uses vars to interpolate. Otherwise, each clause can be a", "svars) def xjoin(a, b): if a and b: return a", "DB(None, {}) >>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True)", "' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT * FROM", "vars=dict(x='f'), _test=True) <sql: \"SELECT * FROM foo WHERE x =", "None else: return out keys = values[0].keys() #@@ make sure", ">>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst else:", "safeunicode(self._str()) def __repr__(self): return '<sql: %s>' % repr(str(self)) class SQLLiteral:", "= text self.pos = pos def __str__(self): return \"unfinished expression", "clauses `where` and `using`. >>> db = DB(None, {}) >>>", "for x in self.items: if isinstance(x, SQLParam): x = x.get_marker(paramstyle)", "def delete(self, table, where, using=None, svars=None, _test=False): \"\"\" Deletes from", "sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1) while pos", "if svars is None: svars = {} if not processed", "clauses = [self.gen_clause(sql, val, svars) for sql, val in sql_clauses", "r\"\"\" Converts any given object to unicode string. >>> safeunicode('hello')", "svars is None: svars = {} where = self._where(where, svars)", "0 while 1: dollar = sformat.find(\"$\", pos) if dollar <", "queries. >>> SQLQuery.join(['a', 'b'], ', ') <sql: 'a, b'> Optinally,", "prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor() if", "def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam = SQLParam", "q.values() [2, 'bob'] \"\"\" def q(x): return \"(\" + x", "sql_query = self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for", "given object to utf-8 encoded string. >>> safestr('hello') 'hello' >>>", "if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount def delete(self, table, where,", "self.items if isinstance(i, SQLParam)] def join(items, sep=' ', prefix=None, suffix=None,", "pass class _ItplError(ValueError): def __init__(self, text, pos): ValueError.__init__(self) self.text =", "obj is None: return 'NULL' elif obj is True: return", "for v in values] if seqname is False: return None", "= self._db_cursor() self._db_execute(db_cursor, query) if not self.ctx.transactions: self.ctx.commit() return db_cursor.rowcount", "= 3\"> >>> 'WHERE x = ' + sqlquote(True) +", "# make sure all rows have same keys. for v", ">>> q <sql: \"INSERT INTO foo (age, name, created) VALUES", "return None else: return out keys = values[0].keys() #@@ make", "test WHERE name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"]", ">>> q = db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q", "\"\"\" return [i.value for i in self.items if isinstance(i, SQLParam)]", "`order`, `group`, `limit`, and `offset`. Uses vars to interpolate. Otherwise,", "target=sql_query, prefix=\"(\", suffix=\")\") if _test: return sql_query db_cursor = self._db_cursor()", "SQLQuery. \"\"\" if target is None: target = SQLQuery() target_items", "= 't' AND y = 3\"> >>> 'WHERE x =", "\"\"\" if not values: return [] if not self.supports_multiple_insert: out", "q = db.update('foo', where='name = $name', name='bob', age=2, ... created=SQLLiteral('NOW()'),", "t is str: return obj.decode(encoding) elif t in [int, float,", "rows into `tablename`. The `values` must be a list of", "items) def __radd__(self, other): if isinstance(other, basestring): items = [other]", "FROM test WHERE name='joe'\"> >>> q.query() 'SELECT * FROM test", "'x'> >>> q = SQLQuery(['SELECT * FROM ', 'test', '", "Inserts multiple rows into `tablename`. The `values` must be a", "level = dollar + 2, 1 while level: match, pos", "[{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>> db.multiple_insert('person',", "'a', 'b': 'b'}).query() 'a = %s AND b = %s'", "SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT", "foo WHERE x = 'f'\"> >>> db.query(\"SELECT * FROM foo", "out def update(self, tables, where, svars=None, _test=False, **values): \"\"\" Update", "[other] else: return NotImplemented return SQLQuery(items + self.items) def __iadd__(self,", "if '%' in x and '%%' not in x: x", "= list(items.items) else: self.items = [items] # Take care of", "Returns the query part of the sql query. >>> q", "for v in values: if v.keys() != keys: raise ValueError,", "x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is", "3]) <sql: \"WHERE x = 't' AND y IN (2,", "query(self, paramstyle=None): \"\"\" Returns the query part of the sql", "each with the same set of keys. Returns the list", "to interpolate. Otherwise, each clause can be a SQLQuery. >>>", "itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given", "'NULL' elif obj is True: return \"'t'\" elif obj is", "True: return \"'t'\" elif obj is False: return \"'f'\" elif", "'3' \"\"\" # because `1 == True and hash(1) ==", "return '<sql: %s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a", "' USING ' + sqllist(using) if where: q += '", "except Exception: out = None if not self.ctx.transactions: self.ctx.commit() return", "it result = [] for live, chunk in _interpolate(string_): if", "svars = {} where = self._where(where, svars) query = (", "foo (age, name, created) VALUES (%s, %s, NOW())' >>> q.values()", "keyword argument `vars` and the function will call reparam for", "if _test: return query db_cursor = self._db_cursor() self._db_execute(db_cursor, query) if", "pass else: where = reparam(where, svars) return where def select(self,", "to be inserted, each with the same set of keys.", "self.items = [] elif isinstance(items, list): self.items = items elif", "where[1]) elif isinstance(where, SQLQuery): pass else: where = reparam(where, svars)", "+ 1 + (nextchar == \"$\") if pos < len(sformat):", "`tablename`. The `values` must be a list of dictioanries, one", "seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`. The `values`", "unicode: return obj elif t is str: return obj.decode(encoding) elif", "SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>>", "name = 'Joe'\"> \"\"\" if svars is None: svars =", "if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item) if suffix: target_items.append(suffix) return", "db.insert('foo', name='bob', age=2, created=SQLLiteral('NOW()'), _test=True) >>> q <sql: \"INSERT INTO", "value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items =", "self.pos) class SQLParam(object): \"\"\" Parameter in SQLQuery. >>> q =", "test WHERE name=?' \"\"\" s = [] for x in", "obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts the arguments for", "else: nout = reparam(val, svars) def xjoin(a, b): if a", "to an SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3})", "+ 1:pos])) else: chunks.append((0, sformat[pos:dollar + 1])) pos = dollar", "return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\" converts", "pos) if match is None: raise _ItplError(text, pos) return match,", "if suffix: target_items.append(suffix) return target join = staticmethod(join) def _str(self):", "% characters in the query # For backward compatability, ignore", "name = %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if", "\"<EMAIL>\"}] >>> db.multiple_insert('person', values=values, _test=True) <sql: \"INSERT INTO person (name,", "seqname=seqname, _test=_test, **v) for v in values] if seqname is", "sformat[pos:])) return chunks def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts", "paramstyles (currently supported: qmark, numeric, format, pyformat) \"\"\" pass class", "for each row to be inserted, each with the same", "name=?' \"\"\" s = [] for x in self.items: if", "= target.items if prefix: target_items.append(prefix) for i, item in enumerate(items):", "self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in", "dictionary to the keyword argument `vars` and the function will", "name, created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO", "<sql: 'x'> >>> q = SQLQuery(['SELECT * FROM ', 'test',", "<sql: '1'> \"\"\" if items is None: self.items = []", "\"\"\" converts `obj` to its proper SQL version >>> sqlify(None)", "u'abc' \"\"\" if isinstance(lst, basestring): return lst else: return ',", "should be evaled or not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping", "where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where", "def sqlwhere(dictionary, grouping=' AND '): \"\"\" Converts a `dictionary` to", "q = SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=',", "# because `1 == True and hash(1) == hash(True)` #", "= [] for x in self.items: if isinstance(x, SQLParam): x", "else: target_items.append(item) if suffix: target_items.append(suffix) return target join = staticmethod(join)", "%s>' % repr(str(self)) class SQLLiteral: \"\"\" Protects a string from", "{} where = self._where(where, svars) query = ( \"UPDATE \"", "svars=None, _test=False): \"\"\" Deletes from `table` with clauses `where` and", "datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8')", "None or paramstyle in ['format', 'pyformat']: return '%s' raise UnknownParamstyle,", "and `using`. >>> db = DB(None, {}) >>> name =", "consists of `items`, which is a list of strings and", "'a, b' >>> sqllist('a') 'a' >>> sqllist(u'abc') u'abc' \"\"\" if", "enumerate(self.items): if isinstance(item, SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v", "sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v): self.v = v", "bool]: return unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return", "SQLQuery): items = other.items else: return NotImplemented return SQLQuery(self.items +", "x = safestr(x) # automatically escape % characters in the", "live, chunk in _interpolate(string_): if live: v = eval(chunk, dictionary)", "= SQLQuery(['SELECT * FROM ', 'test', ' WHERE x=', SQLParam(1)])", "'SELECT * FROM foo, bar WHERE foo.bar_id = bar.id LIMIT", "SQLQuery): pass else: where = reparam(where, svars) return where def", "[1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if items is None:", "* FROM foo\", _test=True) <sql: 'SELECT * FROM foo'> >>>", "except (ValueError, TypeError): return self.query() def __str__(self): return safestr(self._str()) def", "sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id =", "else: where = reparam(where, svars) return where def select(self, tables,", "at char %d\" % ( repr(self.text), self.pos) class SQLParam(object): \"\"\"", ">>> sqlquote('NOW()') <sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def", ">>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self, value):", "dictionary.items()], grouping) def reparam(string_, dictionary): \"\"\" Takes a string and", "if _test: return sql_query db_cursor = self._db_cursor() if seqname is", "a `reparam`-style list to use instead of interpolating. >>> db", "and SQLParams, which get concatenated to produce the actual query.", "list of ids of the inserted rows. Set `seqname` to", "= safestr(x) # automatically escape % characters in the query", "\"id = \" + sqlparam(where) elif isinstance(where, (list, tuple)) and", ">>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id", "long)): if sql == 'WHERE': nout = 'id = '", "the keyword argument `vars` and the function will call reparam", "if isinstance(val, (int, long)): if sql == 'WHERE': nout =", "= %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars", "# tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates a", "2, 1 while level: match, pos = matchorfail(sformat, pos) tstart,", "the result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s =", "'Joe'\"> \"\"\" if svars is None: svars = {} where", "return out keys = values[0].keys() #@@ make sure all keys", ">>> q.values() [2, 'bob', 'Joseph'] \"\"\" if svars is None:", "__str__(self): return str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value)", "def gen_clause(self, sql, val, svars): if isinstance(val, (int, long)): if", "where, group, order, limit, offset): return ( ('SELECT', what), ('FROM',", "i in self.items if isinstance(i, SQLParam)] def join(items, sep=' ',", "INTO %s DEFAULT VALUES\" % table def multiple_insert(self, tablename, values,", "_test=True) <sql: 'SELECT * FROM foo'> >>> db.select(['foo', 'bar'], where=\"foo.bar_id", "<sql: \"'NOW()'\"> >>> sqlquote(SQLLiteral('NOW()')) <sql: 'NOW()'> \"\"\" def __init__(self, v):", "%s, NOW())' >>> q.values() [2, 'bob'] \"\"\" def q(x): return", "self._where(where, svars) q = 'DELETE FROM ' + table if", "limit=None, offset=None, _test=False): \"\"\" Selects `what` from `tables` with clauses", "AND y IN ' + sqlquote([2, 3]) <sql: \"WHERE x", "`processed=True`, `vars` is a `reparam`-style list to use instead of", "not self.ctx.transactions: self.ctx.commit() return out def update(self, tables, where, svars=None,", "3, cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a", "= SQLQuery.join([sqlparam(v) for v in values.values()], ', ') sql_query =", "values=values, _test=True) <sql: \"INSERT INTO person (name, email) VALUES ('foo',", "is None: svars = {} sql_clauses = self.sql_clauses(what, tables, where,", "elif obj is True: return \"'t'\" elif obj is False:", "group), ('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self,", "{} if not processed and not isinstance(sql_query, SQLQuery): sql_query =", "dollar + 2, 1 while level: match, pos = matchorfail(sformat,", "AND cust_id = 2'> >>> sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ')", "have to do this the hard way... if obj is", "created = NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE", "+ 1) elif sformat[pos] in \"([\": pos, level = pos", "which get concatenated to produce the actual query. \"\"\" __slots__", "<sql: '(a, b)'> If target argument is provided, the items", "or isinstance(obj, unicode): return unicode(obj) else: return str(obj).decode(encoding) def safestr(obj,", "bar.id\", limit=5, _test=True) <sql: 'SELECT * FROM foo, bar WHERE", "to be made to find # the id of the", "str): return obj elif hasattr(obj, 'next'): # iterator return itertools.imap(safestr,", "'f'\"> \"\"\" if svars is None: svars = {} if", "\" WHERE \" + where) if _test: return query db_cursor", "= items elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items,", "def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to unicode", "level = level - 1 chunks.append((1, sformat[dollar + 2:pos -", "[] if not self.supports_multiple_insert: out = [self.insert(tablename, seqname=seqname, _test=_test, **v)", ">>> q = SQLQuery(['SELECT * FROM ', 'test', ' WHERE", "target is None: target = SQLQuery() target_items = target.items if", "= pos def __str__(self): return \"unfinished expression in %s at", "\"SELECT * FROM foo WHERE x = 'f'\"> \"\"\" if", "seqname) if isinstance(sql_query, tuple): # for some databases, a separate", "'f'\"> >>> db.query(\"SELECT * FROM foo WHERE x = \"", "instead of creating a new SQLQuery. \"\"\" if target is", "Internally, consists of `items`, which is a list of strings", "+ sqllist(using) if where: q += ' WHERE ' +", "clause can be a SQLQuery. >>> db = DB(None, {})", "self.ctx.commit() return db_cursor.rowcount def delete(self, table, where, using=None, svars=None, _test=False):", "= [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\": \"bar\", \"email\": \"<EMAIL>\"}] >>>", "list): return _sqllist(a) else: return sqlparam(a).sqlquery() def _interpolate(sformat): \"\"\" Takes", "_test: return sql_query db_cursor = self._db_cursor() if seqname is not", "out = [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values]", "= 'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql:", "name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE", "v.keys() != keys: raise ValueError, 'Bad data' sql_query = SQLQuery('INSERT", "q.values() ('SELECT * FROM test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1))", "nout) def _where(self, where, svars): if isinstance(where, (int, long)): where", "sql, val in sql_clauses if val is not None] qout", "and '%%' not in x: x = x.replace('%', '%%') s.append(x)", "def query(self, paramstyle=None): \"\"\" Returns the query part of the", "level - 1 else: break chunks.append((1, sformat[dollar + 1:pos])) else:", "SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass else: where = reparam(where,", "age = %s, name = %s, created = NOW() WHERE", "'Joe' >>> db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE", "`vars` and the function will call reparam for you. Internally,", "WHERE name=%s' >>> q.query(paramstyle='qmark') 'SELECT * FROM test WHERE name=?'", "__str__(self): return \"unfinished expression in %s at char %d\" %", "not. from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize", "__init__(self): \"\"\"Creates a database. \"\"\" pass def query(self, sql_query,processed=False, svars=None):", "= db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except Exception: out =", "elif isinstance(other, SQLQuery): self.items.extend(other.items) else: return NotImplemented return self def", "unicode(obj) elif hasattr(obj, '__unicode__') or isinstance(obj, unicode): return unicode(obj) else:", "is None or paramstyle in ['format', 'pyformat']: return '%s' raise", "reparam(where, svars) return where def select(self, tables, svars=None, what='*', where=None,", "in namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar +", "db function. Otherwise, you can pass a dictionary to the", "['format', 'pyformat']: if '%' in x and '%%' not in", "\"\"\" Update `tables` with clause `where` (interpolated using `vars`) and", "setting `values`. >>> db = DB(None, {}) >>> name =", "`1 == True and hash(1) == hash(True)` # we have", "tablename, values, seqname=None, _test=False): \"\"\" Inserts multiple rows into `tablename`.", "... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q <sql: \"UPDATE foo SET", "a + ' ' + b else: return a or", ">>> SQLQuery(\"x\") <sql: 'x'> >>> q = SQLQuery(['SELECT * FROM", "any given object to unicode string. >>> safeunicode('hello') u'hello' >>>", "`what` from `tables` with clauses `where`, `order`, `group`, `limit`, and", "= True >>> values = [{\"name\": \"foo\", \"email\": \"<EMAIL>\"}, {\"name\":", "what, tables, where, group, order, limit, offset): return ( ('SELECT',", "\"\".join(s) def values(self): \"\"\" Returns the values of the parameters", "q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')]) >>>", "suffix=')') <sql: '(a, b)'> If target argument is provided, the", "you can pass a dictionary to the keyword argument `vars`", "`SQLQuery` for the result. >>> reparam(\"s = $s\", dict(s=True)) <sql:", "\"([\": pos, level = pos + 1, 1 while level:", "b: return a + ' ' + b else: return", "svars): if isinstance(where, (int, long)): where = \"id = \"", "pos) tstart, tend = match.regs[3] token = sformat[tstart:tend] if token", "SQLParam(\"joe\")]) >>> q <sql: \"SELECT * FROM test WHERE name='joe'\">", "xjoin(sql, nout) def _where(self, where, svars): if isinstance(where, (int, long)):", "SQLQuery. >>> db = DB(None, {}) >>> db.select('foo', _test=True) <sql:", "'pyformat']: return '%s' raise UnknownParamstyle, paramstyle def sqlquery(self): return SQLQuery([self])", "repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8') return repr(obj)", "because `1 == True and hash(1) == hash(True)` # we", "= SQLParam class SQLQuery(object): \"\"\" You can pass this sort", ">>> safestr(2) '2' \"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif", "while level: match, pos = matchorfail(sformat, pos) tstart, tend =", "one. >>> db = DB(None, {}) >>> db.supports_multiple_insert = True", "return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else:", "sqlwhere({'cust_id': 2, 'order_id':3}, grouping=', ') <sql: 'order_id = 3, cust_id", "return out def update(self, tables, where, svars=None, _test=False, **values): \"\"\"", "isinstance(obj, str): return obj elif hasattr(obj, 'next'): # iterator return", "values from the dictionary. Returns an `SQLQuery` for the result.", "i != 0: target_items.append(sep) if isinstance(item, SQLQuery): target_items.extend(item.items) else: target_items.append(item)", "arguments can be provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(',", "prefix: target_items.append(prefix) for i, item in enumerate(items): if i !=", ">>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam('joe')])", "def __radd__(self, other): if isinstance(other, basestring): items = [other] else:", "matchorfail(sformat, pos + 1) elif sformat[pos] in \"([\": pos, level", "produce the actual query. \"\"\" __slots__ = [\"items\"] # tested", "('ORDER BY', order), ('LIMIT', limit), ('OFFSET', offset)) def gen_clause(self, sql,", "append(self, value): self.items.append(value) def __add__(self, other): if isinstance(other, basestring): items", "= reparam(sql_query, svars) return sql_query def sql_clauses(self, what, tables, where,", "'test', ' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT *", "for i in self.items if isinstance(i, SQLParam)] def join(items, sep='", "target argument is provided, the items are appended to target", "name = %s, created = NOW() WHERE name = %s'", "def __str__(self): return str(self.value) def __repr__(self): return '<param: %s>' %", "1 chunks.append((1, sformat[dollar + 2:pos - 1])) elif nextchar in", "_sqllist([1, 2, 3]) <sql: '(1, 2, 3)'> \"\"\" items =", "= match.regs[3] token = sformat[tstart:tend] if token[0] in \"([\": level", "__len__(self): return len(self.query()) def query(self, paramstyle=None): \"\"\" Returns the query", "to interpolate it. If `processed=True`, `vars` is a `reparam`-style list", "iterator return itertools.imap(safestr, obj) else: return str(obj) def sqlify(obj): \"\"\"", "safestr(self._str()) def __unicode__(self): return safeunicode(self._str()) def __repr__(self): return '<sql: %s>'", "if using: q += ' USING ' + sqllist(using) if", "if i != 0: sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in", "= self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for some", "str(self.value) def __repr__(self): return '<param: %s>' % repr(self.value) sqlparam =", "2)'> \"\"\" dictionary = dictionary.copy() # eval mucks with it", "u'\\u1234' \"\"\" t = type(obj) if t is unicode: return", "provided. >>> SQLQuery.join(['a', 'b'], ', ', prefix='(', suffix=')') <sql: '(a,", "sql_query) try: out = db_cursor.fetchone()[0] out = range(out-len(values)+1, out+1) except", "\"\"\" if isinstance(obj, unicode): return obj.encode(encoding) elif isinstance(obj, str): return", "q <sql: \"SELECT * FROM test WHERE name='joe'\"> >>> q.query()", "NOW() WHERE name = 'Joseph'\"> >>> q.query() 'UPDATE foo SET", "+ table if using: q += ' USING ' +", "= v def __repr__(self): return self.v class SQLProducer: \"\"\"Database\"\"\" def", "\") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query, prefix=\"(\",", "safeunicode(obj, encoding='utf-8'): r\"\"\" Converts any given object to unicode string.", "unicode): obj = obj.encode('utf8') return repr(obj) def sqllist(lst): \"\"\" Converts", "+ other def __radd__(self, other): return other + self.sqlquery() def", "elif datetime and isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj,", "'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\" if isinstance(obj,", "for i, item in enumerate(items): if i != 0: target_items.append(sep)", "the query # For backward compatability, ignore escaping when the", "= $name', name='bob', age=2, ... created=SQLLiteral('NOW()'), vars=locals(), _test=True) >>> q", "chunks.append((0, sformat[pos:dollar])) pos, level = dollar + 2, 1 while", "return SQLQuery([self]) def __add__(self, other): return self.sqlquery() + other def", "pos, level = dollar + 2, 1 while level: match,", "'a' >>> sqllist(u'abc') u'abc' \"\"\" if isinstance(lst, basestring): return lst", "sequence ID. Set `seqname` to the ID if it's not", "self._process_insert_query(sql_query, tablename, seqname) if isinstance(sql_query, tuple): # for some databases,", "s.append(x) return \"\".join(s) def values(self): \"\"\" Returns the values of", "dollar + 1) while pos < len(sformat): if sformat[pos] ==", "cust_id = 2'> >>> sqlwhere({'a': 'a', 'b': 'b'}).query() 'a =", "the string using values from the dictionary. Returns an `SQLQuery`", "namechars: chunks.append((0, sformat[pos:dollar])) match, pos = matchorfail(sformat, dollar + 1)", "', 'test', ' WHERE x=', SQLParam(1)]) >>> q <sql: 'SELECT", "string. >>> safeunicode('hello') u'hello' >>> safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234'", "(2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo (age, name,", "'1'> \"\"\" if items is None: self.items = [] elif", "sql_query,processed=False, svars=None): \"\"\" Execute SQL query `sql_query` using dictionary `vars`", "\" SET \" + sqlwhere(values, ', ') + \" WHERE", "INTO foo (age, name, created) VALUES (%s, %s, NOW())' >>>", "<sql: 's IN (1, 2)'> \"\"\" dictionary = dictionary.copy() #", "test WHERE x=%s', [1]) >>> SQLQuery(SQLParam(1)) <sql: '1'> \"\"\" if", "if items is None: self.items = [] elif isinstance(items, list):", ">>> reparam(\"s IN $s\", dict(s=[1, 2])) <sql: 's IN (1,", "%s \" % tablename + q(_keys) + ' VALUES '", "= $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo WHERE name", "<sql: \"s = 't'\"> >>> reparam(\"s IN $s\", dict(s=[1, 2]))", "grouping=' AND '): \"\"\" Converts a `dictionary` to an SQL", "SQLParam) and isinstance(item.value, SQLLiteral): self.items[i] = item.value.v def append(self, value):", "prefix and suffix arguments can be provided. >>> SQLQuery.join(['a', 'b'],", "1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar])) pos, level =", "there isn't one. >>> db = DB(None, {}) >>> db.supports_multiple_insert", "+ \")\" if values: _keys = SQLQuery.join(values.keys(), ', ') _values", "', ') + \" WHERE \" + where) if _test:", "from the dictionary. Returns an `SQLQuery` for the result. >>>", "safeunicode(2) u'2' >>> safeunicode('\\xe1\\x88\\xb4') u'\\u1234' \"\"\" t = type(obj) if", "qout return self.query(qout, processed=True) def insert(self, tablename, seqname=None, _test=False, **values):", "VALUES ' + q(_values) else: sql_query = SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query", ">>> q <sql: 'SELECT * FROM test WHERE x=1'> >>>", "where, svars=None, _test=False, **values): \"\"\" Update `tables` with clause `where`", "keys = values[0].keys() #@@ make sure all keys are valid", "= self._where(where, svars) query = ( \"UPDATE \" + sqllist(tables)", "= sformat[dollar + 1] if nextchar == \"{\": chunks.append((0, sformat[pos:dollar]))", "', prefix='(', suffix=')') <sql: '(a, b)'> If target argument is", "used in the sql query. >>> q = SQLQuery([\"SELECT *", "str(obj).decode(encoding) def safestr(obj, encoding='utf-8'): r\"\"\" Converts any given object to", "obj.encode(encoding) elif isinstance(obj, str): return obj elif hasattr(obj, 'next'): #", "where, group, order, limit, offset) clauses = [self.gen_clause(sql, val, svars)", "return a + ' ' + b else: return a", "SQLQuery(self._get_insert_default_values_query(tablename)) return sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s", "SET age = %s, name = %s, created = NOW()", "q = 'DELETE FROM ' + table if using: q", "'Bad data' sql_query = SQLQuery('INSERT INTO %s (%s) VALUES '", "b = %s' \"\"\" return SQLQuery.join([k + ' = '", "= DB(None, {}) >>> name = 'Joe' >>> db.delete('foo', where='name", "is a list of strings and SQLParams, which get concatenated", "the form (boolean, string) where boolean says whether string should", "to the ID if it's not the default, or to", "FROM foo\", _test=True) <sql: 'SELECT * FROM foo'> >>> db.query(\"SELECT", "db.delete('foo', where='name = $name', vars=locals(), _test=True) <sql: \"DELETE FROM foo", "name=%s' >>> q.values() ['joe'] \"\"\" __slots__ = [\"value\"] def __init__(self,", "sformat[pos + 1] in namechars: match, pos = matchorfail(sformat, pos", "(public domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog tokenprog", "pos): ValueError.__init__(self) self.text = text self.pos = pos def __str__(self):", "%s>' % repr(self.value) sqlparam = SQLParam class SQLQuery(object): \"\"\" You", "hard way... if obj is None: return 'NULL' elif obj", "== 2: where = SQLQuery(where[0], where[1]) elif isinstance(where, SQLQuery): pass", "isinstance(other, basestring): items = [other] else: return NotImplemented return SQLQuery(items", "format, pyformat) \"\"\" pass class _ItplError(ValueError): def __init__(self, text, pos):", "= ' + sqlquote(True) + ' AND y = '", "for the result. >>> reparam(\"s = $s\", dict(s=True)) <sql: \"s", "\"\"\" dictionary = dictionary.copy() # eval mucks with it result", "SQLProducer: \"\"\"Database\"\"\" def __init__(self): \"\"\"Creates a database. \"\"\" pass def", "make sure all keys are valid # make sure all", "boolean says whether string should be evaled or not. from", "when the query looks already escaped if paramstyle in ['format',", "return xjoin(sql, nout) def _where(self, where, svars): if isinstance(where, (int,", ">>> sqlify(3) '3' \"\"\" # because `1 == True and", "\"\"\" if target is None: target = SQLQuery() target_items =", "INTO foo (age, name, created) VALUES (2, 'bob', NOW())\"> >>>", "Update `tables` with clause `where` (interpolated using `vars`) and setting", "= [self.insert(tablename, seqname=seqname, _test=_test, **v) for v in values] if", "same set of keys. Returns the list of ids of", "FROM ' + table if using: q += ' USING", "2, 'order_id':3}) <sql: 'order_id = 3 AND cust_id = 2'>", "x + \")\" if values: _keys = SQLQuery.join(values.keys(), ', ')", "elif isinstance(other, SQLQuery): items = other.items else: return NotImplemented return", "foo WHERE x = $x\", vars=dict(x='f'), _test=True) <sql: \"SELECT *", "+= ' WHERE ' + where return q sqlproducer =", "q1) self._db_execute(db_cursor, q2) else: self._db_execute(db_cursor, sql_query) try: out = db_cursor.fetchone()[0]", "elif isinstance(items, SQLParam): self.items = [items] elif isinstance(items, SQLQuery): self.items", "in \")]\": level = level - 1 else: break chunks.append((1,", "def sql_clauses(self, what, tables, where, group, order, limit, offset): return", "'Joseph'\"> >>> q.query() 'UPDATE foo SET age = %s, name", "'): \"\"\" Converts a `dictionary` to an SQL WHERE clause", ">>> q = SQLQuery([\"SELECT * FROM test WHERE name=\", SQLParam(\"joe\")])", "WHERE name = %s' >>> q.values() [2, 'bob', 'Joseph'] \"\"\"", "of SQLLiterals for i, item in enumerate(self.items): if isinstance(item, SQLParam)", "''' import itertools import datetime def safeunicode(obj, encoding='utf-8'): r\"\"\" Converts", "sql_query def _get_insert_default_values_query(self, table): return \"INSERT INTO %s DEFAULT VALUES\"", "= matchorfail(sformat, dollar + 1) while pos < len(sformat): if", "<http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee) \"\"\" from tokenize import tokenprog", "seqname is not False: sql_query = self._process_insert_query(sql_query, tablename, seqname) if", "created) VALUES (2, 'bob', NOW())\"> >>> q.query() 'INSERT INTO foo", "FROM ', 'test', ' WHERE x=', SQLParam(1)]) >>> q <sql:", "[\"items\"] # tested in sqlquote's docstring def __init__(self, items=None): r\"\"\"Creates", "test WHERE name=\", SQLParam('joe')]) >>> q.query() 'SELECT * FROM test", ">>> q.query(), q.values() ('SELECT * FROM test WHERE x=%s', [1])", "\"SELECT * FROM test WHERE name='joe'\"> >>> q.query() 'SELECT *", "None: target = SQLQuery() target_items = target.items if prefix: target_items.append(prefix)", "SQLQuery(items + self.items) def __iadd__(self, other): if isinstance(other, (basestring, SQLParam)):", ">>> safestr('hello') 'hello' >>> safestr(u'\\u1234') '\\xe1\\x88\\xb4' >>> safestr(2) '2' \"\"\"", "isn't one. >>> db = DB(None, {}) >>> q =", "v in values] if seqname is False: return None else:", "return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj = obj.encode('utf8') return", "(%s) VALUES ' % (tablename, ', '.join(keys))) for i, row", "+ sqlquote(True) + ' AND y = ' + sqlquote(3)", "items.append(sqlparam(v)) items.append(')') return SQLQuery(items) def sqlquote(a): \"\"\" Ensures `a` is", "is False: return \"'f'\" elif datetime and isinstance(obj, datetime.datetime): return", "isinstance(obj, datetime.datetime): return repr(obj.isoformat()) else: if isinstance(obj, unicode): obj =", "SQLParam('joe')]) >>> q.query() 'SELECT * FROM test WHERE name=%s' >>>", "def _str(self): try: return self.query() % tuple([sqlify(x) for x in", "sql_query.append(\", \") SQLQuery.join([SQLParam(row[k]) for k in keys], sep=\", \", target=sql_query,", "escape % characters in the query # For backward compatability,", "a SQL query. >>> 'WHERE x = ' + sqlquote(True)", "limit, offset) clauses = [self.gen_clause(sql, val, svars) for sql, val", "isinstance(val, (list, tuple)) and len(val) == 2: nout = SQLQuery(val[0],", "SQL WHERE clause `SQLQuery`. >>> sqlwhere({'cust_id': 2, 'order_id':3}) <sql: 'order_id" ]
[ "production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run", "'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME':", "For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the", "os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } }", "= True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES =", "for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement)", "'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env", "settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY", "via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = {", "'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement,", "is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del", "of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build", "secret key used in production secret! SECRET_KEY = '<KEY> #", "development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ #", "# https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE", "'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER", "ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':", "WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = {", "'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',", "# Build paths inside the project like this: os.path.join(BASE_DIR, ...)", "= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production", "JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,", "production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', ] #", "] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',", "'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell',", "'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF", "'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions', 'django_extensions'),", "#'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND':", "'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]:", "pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR", "continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',", "settings for dddppp project. Generated by 'django-admin startproject' using Django", "_PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start", "Build paths inside the project like this: os.path.join(BASE_DIR, ...) import", "( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware',", "_PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env]))", "'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth)", "= True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE =", "'django-admin startproject' using Django 1.8.2. For more information on this", "see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project like", "the project like this: os.path.join(BASE_DIR, ...) import os import pkg_resources", "set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] =", "pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',", "= '<KEY> # SECURITY WARNING: don't run with debug turned", "# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL =", "pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except (", "SECURITY WARNING: don't run with debug turned on in production!", "os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST',", "see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT", "Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/'", "= str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))", "import pwd PROJECT_NAME = 'dddppp' # Enforce a valid POSIX", "os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''),", "SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True", "\"\"\" # Build paths inside the project like this: os.path.join(BASE_DIR,", "the secret key used in production secret! SECRET_KEY = '<KEY>", "POSIX environment # Get missing environment variables via call to", "TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ", "SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with debug", "os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd PROJECT_NAME =", "like this: os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd", "import os import pkg_resources import pwd PROJECT_NAME = 'dddppp' #", "file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and", "} for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE", "] for (requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try:", "try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES", "in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't", "for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True", "call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME':", "USE_I18N = True USE_L10N = True USE_TZ = True #", "a valid POSIX environment # Get missing environment variables via", "= 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more options", "# Enforce a valid POSIX environment # Get missing environment", "https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE',", "# see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')", "startproject' using Django 1.8.2. For more information on this file,", "debug turned on in production! DEBUG = True ALLOWED_HOSTS =", "'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [", "in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound,", "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME),", "= True ALLOWED_HOSTS = [ 'localhost', ] # Application definition", "for dddppp project. Generated by 'django-admin startproject' using Django 1.8.2.", "by 'django-admin startproject' using Django 1.8.2. For more information on", "https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project like this:", "...) import os import pkg_resources import pwd PROJECT_NAME = 'dddppp'", "see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their", "= True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/", "= 'dddppp' # Enforce a valid POSIX environment # Get", "https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True", "] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',", "'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL':", "\"\"\" Django settings for dddppp project. Generated by 'django-admin startproject'", "unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep", "- unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING:", "= { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER':", "} # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE =", "'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for", "] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES =", "'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD',", "# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key", "# Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':", "}, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES", "'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls'", "secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with", "'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES = [ {", "inside the project like this: os.path.join(BASE_DIR, ...) import os import", "in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost', ]", "'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',", "'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for", "#SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE", "_PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name',", "= None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME':", "None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE,", "Django settings for dddppp project. Generated by 'django-admin startproject' using", "'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application'", "pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce a valid", "os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production #", "'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is", "'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ]", "STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'", "'dddppp' # Enforce a valid POSIX environment # Get missing", "'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True", "= 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N =", "# https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':", "True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = []", "= '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' #", "_PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings -", "'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF =", "# SECURITY WARNING: don't run with debug turned on in", "full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\"", "'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',", "'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',", "with debug turned on in production! DEBUG = True ALLOWED_HOSTS", "True ALLOWED_HOSTS = [ 'localhost', ] # Application definition INSTALLED_APPS", "STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/ for more", "= { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid',", "Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N", "using Django 1.8.2. For more information on this file, see", "('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ):", "= ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY", "SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT", "their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the", "'PORT': os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE", "= pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd", "[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts',", "pwd PROJECT_NAME = 'dddppp' # Enforce a valid POSIX environment", "'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''),", "in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env]", "del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development", "# Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC'", "For the full list of settings and their values, see", "and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside", "None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name',", "[ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ]", "'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [", "'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides',", "'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']),", "pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable", "'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' #", "for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the", "_PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP,", "{ 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER',", "Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')", "USE_L10N = True USE_TZ = True # Static files (CSS,", "options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF =", "'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES =", "''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/", "True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True", "os.environ.get('PGPORT', ''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE =", "True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ],", "turned on in production! DEBUG = True ALLOWED_HOSTS = [", "Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2',", "Get missing environment variables via call to pwd.getpwuid(...) _PW_CACHE =", "on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of", "pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name', 'USER':", "'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True", "WARNING: keep the secret key used in production secret! SECRET_KEY", "pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',", "the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/", "= 'UTC' USE_I18N = True USE_L10N = True USE_TZ =", "DEBUG = True ALLOWED_HOSTS = [ 'localhost', ] # Application", "import pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce a", "project. Generated by 'django-admin startproject' using Django 1.8.2. For more", "'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database", "BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for", "SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES", "'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization", "[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {", "production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret", "paths inside the project like this: os.path.join(BASE_DIR, ...) import os", "SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY", "'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'dddppp.urls' TEMPLATES", "key used in production secret! SECRET_KEY = '<KEY> # SECURITY", "for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE =", "information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list", "[], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',", "'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', }", "= True USE_TZ = True # Static files (CSS, JavaScript,", "except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [", "'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in [ ('django-extensions',", "= [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware',", "= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS':", "= 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default':", "Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',", "Enforce a valid POSIX environment # Get missing environment variables", "USE_TZ = True # Static files (CSS, JavaScript, Images) #", "don't run with debug turned on in production! DEBUG =", "(requirement, pth) in [ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except", "_PW_MAP = { 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID':", "{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD':", "'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], },", "SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))", "{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':", "valid POSIX environment # Get missing environment variables via call", "Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/", "settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths", "} } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE", "'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT':", "variables via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP =", "= [ 'localhost', ] # Application definition INSTALLED_APPS = [", "dddppp project. Generated by 'django-admin startproject' using Django 1.8.2. For", "True USE_L10N = True USE_TZ = True # Static files", "'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS':", "os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see: https://github.com/carljm/django-secure/", "[ ('django-extensions', 'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict,", "missing environment variables via call to pwd.getpwuid(...) _PW_CACHE = None", "SECURITY WARNING: keep the secret key used in production secret!", "STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure #", "True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True", "'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid',", "project like this: os.path.join(BASE_DIR, ...) import os import pkg_resources import", "= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp', 'dddp.server',", "_PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings", "this: os.path.join(BASE_DIR, ...) import os import pkg_resources import pwd PROJECT_NAME", "{ 'LOGNAME': 'pw_name', 'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID':", "''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } #", "'django_extensions'), ]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue", "'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE", "_missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid())", "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',", "'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]", "os import pkg_resources import pwd PROJECT_NAME = 'dddppp' # Enforce", "[ 'localhost', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin',", "https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in", "LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N", "}, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases", "{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },", "# Get missing environment variables via call to pwd.getpwuid(...) _PW_CACHE", "'django.contrib.staticfiles', 'dddp', 'dddp.server', 'dddp.accounts', 'dddppp.slides', ] for (requirement, pth) in", "'<KEY> # SECURITY WARNING: don't run with debug turned on", "= 'dddppp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [],", "'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ):", "'UTC' USE_I18N = True USE_L10N = True USE_TZ = True", "MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',", "more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF", "on in production! DEBUG = True ALLOWED_HOSTS = [ 'localhost',", "[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION", "ALLOWED_HOSTS = [ 'localhost', ] # Application definition INSTALLED_APPS =", "files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT", "'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), }", "os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT',", "PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST': os.environ.get('PGHOST', ''),", "= True SECURE_FRAME_DENY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY =", "environment variables via call to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP", "Generated by 'django-admin startproject' using Django 1.8.2. For more information", "# Quick-start development settings - unsuitable for production # See", "if _PW_CACHE is None: _PW_CACHE = pwd.getpwuid(os.getuid()) os.environ[_missing_env] = str(getattr(_PW_CACHE,", "'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if _PW_CACHE is None:", "str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #", "os.environ.get('PGHOST', ''), 'PORT': os.environ.get('PGPORT', ''), } } # Internationalization #", "https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values,", "pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES =", "]: try: pkg_resources.get_distribution(requirement) except ( pkg_resources.DistributionNotFound, pkg_resources.VersionConflict, ): continue INSTALLED_APPS.append(pth)", "os.environ[_missing_env] = str(getattr(_PW_CACHE, _PW_MAP[_missing_env])) del _PW_CACHE, _PW_MAP, pwd BASE_DIR =", "# https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au' TIME_ZONE = 'UTC' USE_I18N =", "https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT =", "WARNING: don't run with debug turned on in production! DEBUG", "True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL", "'dddppp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': {", "values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" # Build paths inside the project", "'USER': 'pw_name', 'USERNAME': 'pw_name', 'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir',", "'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION =", "run with debug turned on in production! DEBUG = True", "list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ \"\"\" #", "'/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure", "= os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # django-secure # see:", "django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO',", "# SECURITY WARNING: keep the secret key used in production", "environment # Get missing environment variables via call to pwd.getpwuid(...)", "'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in set(_PW_MAP).difference(os.environ): if", "used in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING:", "more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full", "See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used", "to pwd.getpwuid(...) _PW_CACHE = None _PW_MAP = { 'LOGNAME': 'pw_name',", "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dddp',", "True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),", "= True SESSION_COOKIE_HTTPONLY = True DDDPPP_CONTENT_TYPES = [] PROJ_ROOT =", "'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [", "], }, }, ] WSGI_APPLICATION = 'dddppp.wsgi.application' # Database #", "INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',", "('HTTP_X_FORWARDED_PROTO', 'https') #SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_FRAME_DENY =", "definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',", "True USE_TZ = True # Static files (CSS, JavaScript, Images)", "https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE =", "Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/", "'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for _missing_env in", "'UID': 'pw_uid', 'GID': 'pw_gid', 'HOME': 'pw_dir', 'SHELL': 'pw_shell', } for", "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True,", "'NAME': os.environ.get('PGDATABASE', PROJECT_NAME), 'USER': os.environ.get('PGUSER', os.environ['LOGNAME']), 'PASSWORD': os.environ.get('DJANGO_DATABASE_PASSWORD', ''), 'HOST':", "# django-secure # see: https://github.com/carljm/django-secure/ for more options SECURE_PROXY_SSL_HEADER =", "PROJECT_NAME = 'dddppp' # Enforce a valid POSIX environment #", "this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings", "''), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-au'", "keep the secret key used in production secret! SECRET_KEY =", "): continue INSTALLED_APPS.append(pth) MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',", "= True USE_L10N = True USE_TZ = True # Static", "1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For", "(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT =" ]
[ "System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language", "around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read()", "long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License ::", "wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__),", "test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved ::", "[ 'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version", "install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>',", "Python :: 2.6\", \"Programming Language :: Python :: 2.7\", \"Programming", "Language :: Python :: 2.7\", \"Programming Language :: Python ::", "\"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools',", "__doc__ = \"\"\" Command line tool and library wrappers around", "except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>',", "from setuptools import setup import os __doc__ = \"\"\" Command", "Approved :: BSD License\", \"Topic :: System :: Networking\", \"Operating", "Language :: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/', ['extras/wifi-completion.bash']), ]", "= \"\"\" Command line tool and library wrappers around iwlist", "'1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'],", ":: OSI Approved :: BSD License\", \"Topic :: System ::", "\"Topic :: System :: Networking\", \"Operating System :: POSIX ::", ":: 2.7\", \"Programming Language :: Python :: 3.3\", ], data_files=[", "\"Environment :: Console\", \"Programming Language :: Python\", \"Programming Language ::", "packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI", "<filename>setup.py #!/usr/bin/env python from setuptools import setup import os __doc__", "Networking\", \"Operating System :: POSIX :: Linux\", \"Environment :: Console\",", "\"Programming Language :: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/', ['extras/wifi-completion.bash']),", "'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version = '1.0.0'", "def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2',", "classifiers=[ \"License :: OSI Approved :: BSD License\", \"Topic ::", "= '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'),", "\"Operating System :: POSIX :: Linux\", \"Environment :: Console\", \"Programming", "/etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [", "\"Programming Language :: Python\", \"Programming Language :: Python :: 2.6\",", ":: POSIX :: Linux\", \"Environment :: Console\", \"Programming Language ::", "<NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires,", "\"Programming Language :: Python :: 2.6\", \"Programming Language :: Python", "scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved", ":: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/', ['extras/wifi-completion.bash']), ] )", "\"\"\" Command line tool and library wrappers around iwlist and", "POSIX :: Linux\", \"Environment :: Console\", \"Programming Language :: Python\",", "and library wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname):", ":: BSD License\", \"Topic :: System :: Networking\", \"Operating System", "return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try:", "Python :: 2.7\", \"Programming Language :: Python :: 3.3\", ],", "author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD',", "argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version, author='<NAME>,", "Linux\", \"Environment :: Console\", \"Programming Language :: Python\", \"Programming Language", "Language :: Python\", \"Programming Language :: Python :: 2.6\", \"Programming", ":: System :: Networking\", \"Operating System :: POSIX :: Linux\",", "System :: Networking\", \"Operating System :: POSIX :: Linux\", \"Environment", "library wrappers around iwlist and /etc/network/interfaces. \"\"\" def read(fname): return", "2.6\", \"Programming Language :: Python :: 2.7\", \"Programming Language ::", "License\", \"Topic :: System :: Networking\", \"Operating System :: POSIX", "\"Programming Language :: Python :: 2.7\", \"Programming Language :: Python", "install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD License\", \"Topic", "Command line tool and library wrappers around iwlist and /etc/network/interfaces.", "and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires =", ":: Python\", \"Programming Language :: Python :: 2.6\", \"Programming Language", "BSD License\", \"Topic :: System :: Networking\", \"Operating System ::", "= [ 'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse')", ":: Console\", \"Programming Language :: Python\", \"Programming Language :: Python", "setuptools import setup import os __doc__ = \"\"\" Command line", "Console\", \"Programming Language :: Python\", \"Programming Language :: Python ::", "import os __doc__ = \"\"\" Command line tool and library", "fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try: import argparse", ":: Linux\", \"Environment :: Console\", \"Programming Language :: Python\", \"Programming", "2.7\", \"Programming Language :: Python :: 3.3\", ], data_files=[ ('/etc/bash_completion.d/',", "open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ] try: import", "tool and library wrappers around iwlist and /etc/network/interfaces. \"\"\" def", "import setup import os __doc__ = \"\"\" Command line tool", "python from setuptools import setup import os __doc__ = \"\"\"", "Language :: Python :: 2.6\", \"Programming Language :: Python ::", ":: 2.6\", \"Programming Language :: Python :: 2.7\", \"Programming Language", "line tool and library wrappers around iwlist and /etc/network/interfaces. \"\"\"", ":: Networking\", \"Operating System :: POSIX :: Linux\", \"Environment ::", "version = '1.0.0' setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__,", "iwlist and /etc/network/interfaces. \"\"\" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires", "os __doc__ = \"\"\" Command line tool and library wrappers", "OSI Approved :: BSD License\", \"Topic :: System :: Networking\",", "Python\", \"Programming Language :: Python :: 2.6\", \"Programming Language ::", "license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD License\",", "read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() install_requires = [ 'setuptools', 'pbkdf2', ]", "\"License :: OSI Approved :: BSD License\", \"Topic :: System", ":: Python :: 2.7\", \"Programming Language :: Python :: 3.3\",", "name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests',", "'setuptools', 'pbkdf2', ] try: import argparse except: install_requires.append('argparse') version =", "version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"],", "setup( name='wifi', version=version, author='<NAME>, <NAME>', author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'],", "description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License", "install_requires = [ 'setuptools', 'pbkdf2', ] try: import argparse except:", ":: Python :: 2.6\", \"Programming Language :: Python :: 2.7\",", "import argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi', version=version,", "#!/usr/bin/env python from setuptools import setup import os __doc__ =", "setup import os __doc__ = \"\"\" Command line tool and", "] try: import argparse except: install_requires.append('argparse') version = '1.0.0' setup(", "author_email='<EMAIL>', description=__doc__, long_description=read('README.rst'), packages=['wifi'], scripts=['bin/wifi'], test_suite='tests', platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[", "platforms=[\"Debian\"], license='BSD', install_requires=install_requires, classifiers=[ \"License :: OSI Approved :: BSD", "try: import argparse except: install_requires.append('argparse') version = '1.0.0' setup( name='wifi'," ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions,", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "schema_utils from auth_api.services import Product as ProductService from auth_api.tracer import", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "Unless required by applicable law or agreed to in writing,", "'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response,", "JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as", "exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return", "from auth_api.schemas import utils as schema_utils from auth_api.services import Product", "products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('',", "Province of British Columbia # # Licensed under the Apache", "return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if", "of British Columbia # # Licensed under the Apache License,", "the License is distributed on an 'AS IS' BASIS, #", "else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except", "@staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product", "= ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status =", "the Apache License, Version 2.0 (the 'License'); # you may", "the specific language governing permissions and # limitations under the", "cors from auth_api import status as http_status from auth_api.exceptions import", "auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import", "@cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "under the Apache License, Version 2.0 (the 'License'); # you", "auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import", "Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class", "\"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def", "distributed under the License is distributed on an 'AS IS'", "def post(org_id): \"\"\"Post a new product subscription to the org", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "request_json) if subscriptions is None: response, status = {'message': 'Not", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "from flask import request from flask_restplus import Namespace, Resource, cors", "under the License. \"\"\"API endpoints for managing an Org resource.\"\"\"", "ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import Role from", "status as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import", "not use this file except in compliance with the License.", "IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "permissions and # limitations under the License. \"\"\"API endpoints for", "@_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription to the", "http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED", "post(org_id): \"\"\"Post a new product subscription to the org using", "\"\"\"Post a new product subscription to the org using the", "Apache License, Version 2.0 (the 'License'); # you may not", "import Namespace, Resource, cors from auth_api import status as http_status", "org using the request body.\"\"\" request_json = request.get_json() valid_format, errors", "2019 Province of British Columbia # # Licensed under the", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\"", "you may not use this file except in compliance with", "flask_restplus import Namespace, Resource, cors from auth_api import status as", "using the request body.\"\"\" request_json = request.get_json() valid_format, errors =", "= Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT", "perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions':", "language governing permissions and # limitations under the License. \"\"\"API", "request body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription')", "managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post", "@cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription to", "from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API =", "# distributed under the License is distributed on an 'AS", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema", "Org resource.\"\"\" from flask import request from flask_restplus import Namespace,", "description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance()", "management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET',", "many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status =", "managing an Org resource.\"\"\" from flask import request from flask_restplus", "ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status = {'message':", "the org using the request body.\"\"\" request_json = request.get_json() valid_format,", "from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas", "import cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER", "status = {'code': exception.code, 'message': exception.message}, exception.status_code return response, status", "subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new", "CONDITIONS OF ANY KIND, either express or implied. # See", "\\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\", "utils as schema_utils from auth_api.services import Product as ProductService from", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "auth_api.schemas import utils as schema_utils from auth_api.services import Product as", "ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from auth_api.services import", "JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for", "or implied. # See the License for the specific language", "endpoints for managing an Org resource.\"\"\" from flask import request", "License. # You may obtain a copy of the License", "from auth_api import status as http_status from auth_api.exceptions import BusinessException", "# You may obtain a copy of the License at", "the License. \"\"\"API endpoints for managing an Org resource.\"\"\" from", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils", "valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json)", "response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException", "License, Version 2.0 (the 'License'); # you may not use", "product subscription to the org using the request body.\"\"\" request_json", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License for the specific language governing permissions and # limitations", "from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas", "schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try:", "if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions =", "from auth_api.services import Product as ProductService from auth_api.tracer import Tracer", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "auth_api.tracer import Tracer from auth_api.utils.roles import Role from auth_api.utils.util import", "new product subscription to the org using the request body.\"\"\"", "_JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource):", "if subscriptions is None: response, status = {'message': 'Not authorized", "on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)},", "{'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response,", "an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "= schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST", "cors_preflight API = Namespace('products', description='Endpoints for products management') TRACER =", "response, status = {'message': 'Not authorized to perform this action'},", "to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status =", "an Org resource.\"\"\" from flask import request from flask_restplus import", "# limitations under the License. \"\"\"API endpoints for managing an", "resource.\"\"\" from flask import request from flask_restplus import Namespace, Resource,", "for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id):", "Copyright © 2019 Province of British Columbia # # Licensed", "import Role from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints", "the License for the specific language governing permissions and #", "\\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code':", "# you may not use this file except in compliance", "'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "either express or implied. # See the License for the", "OR CONDITIONS OF ANY KIND, either express or implied. #", "'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not", "Version 2.0 (the 'License'); # you may not use this", "governing permissions and # limitations under the License. \"\"\"API endpoints", "in compliance with the License. # You may obtain a", "http_status.HTTP_201_CREATED except BusinessException as exception: response, status = {'code': exception.code,", "None: response, status = {'message': 'Not authorized to perform this", "software # distributed under the License is distributed on an", "Product as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import", "except BusinessException as exception: response, status = {'code': exception.code, 'message':", "import status as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper", "subscription to the org using the request body.\"\"\" request_json =", "OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value])", "import Tracer from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight", "request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return", "status = {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as", "# # Unless required by applicable law or agreed to", "valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message':", "Licensed under the Apache License, Version 2.0 (the 'License'); #", "# Licensed under the Apache License, Version 2.0 (the 'License');", "from flask_restplus import Namespace, Resource, cors from auth_api import status", "auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API = Namespace('products',", "not valid_format: return {'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id,", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*')", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "for products management') TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS')", "is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES", "as schema_utils from auth_api.services import Product as ProductService from auth_api.tracer", "errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format: return {'message': schema_utils.serialize(errors)},", "'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod", "law or agreed to in writing, software # distributed under", "from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products", "API = Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance()", "for managing an Org resource.\"\"\" from flask import request from", "BusinessException as exception: response, status = {'code': exception.code, 'message': exception.message},", "Role from auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for", "authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else: response, status", "a new product subscription to the org using the request", "flask import request from flask_restplus import Namespace, Resource, cors from", "from auth_api.tracer import Tracer from auth_api.utils.roles import Role from auth_api.utils.util", "© 2019 Province of British Columbia # # Licensed under", "as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles import Role", "schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is", "# Copyright © 2019 Province of British Columbia # #", "implied. # See the License for the specific language governing", "try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response,", "import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils", "under the License is distributed on an 'AS IS' BASIS,", "request from flask_restplus import Namespace, Resource, cors from auth_api import", "<gh_stars>0 # Copyright © 2019 Province of British Columbia #", "import Product as ProductService from auth_api.tracer import Tracer from auth_api.utils.roles", "as http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper", "body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if", "= {'subscriptions': ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception:", "http_status from auth_api.exceptions import BusinessException from auth_api.jwt_wrapper import JWTWrapper from", "to the org using the request body.\"\"\" request_json = request.get_json()", "British Columbia # # Licensed under the Apache License, Version", "import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from auth_api.services", "Namespace('products', description='Endpoints for products management') TRACER = Tracer.get_instance() _JWT =", "Namespace, Resource, cors from auth_api import status as http_status from", "import utils as schema_utils from auth_api.services import Product as ProductService", "by applicable law or agreed to in writing, software #", "and # limitations under the License. \"\"\"API endpoints for managing", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "BusinessException from auth_api.jwt_wrapper import JWTWrapper from auth_api.schemas import ProductSubscriptionSchema from", "response, status = {'code': exception.code, 'message': exception.message}, exception.status_code return response,", "Columbia # # Licensed under the Apache License, Version 2.0", "License. \"\"\"API endpoints for managing an Org resource.\"\"\" from flask", "is None: response, status = {'message': 'Not authorized to perform", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "2.0 (the 'License'); # you may not use this file", "for the specific language governing permissions and # limitations under", "(the 'License'); # you may not use this file except", "auth_api.services import Product as ProductService from auth_api.tracer import Tracer from", "auth_api.utils.util import cors_preflight API = Namespace('products', description='Endpoints for products management')", "status = {'message': 'Not authorized to perform this action'}, \\", "to in writing, software # distributed under the License is", "@TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a new product subscription", "auth_api import status as http_status from auth_api.exceptions import BusinessException from", "ProductSubscriptionSchema().dump(subscriptions, many=True)}, \\ http_status.HTTP_201_CREATED except BusinessException as exception: response, status", "auth_api.schemas import ProductSubscriptionSchema from auth_api.schemas import utils as schema_utils from", "# See the License for the specific language governing permissions", "'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product subscriptions.\"\"\" @staticmethod @TRACER.trace()", "the request body.\"\"\" request_json = request.get_json() valid_format, errors = schema_utils.validate(request_json,", "= JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource", "= Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST', 'OPTIONS'])", "You may obtain a copy of the License at #", "as exception: response, status = {'code': exception.code, 'message': exception.message}, exception.status_code", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "\"\"\"API endpoints for managing an Org resource.\"\"\" from flask import", "@API.route('', methods=['GET', 'POST', 'OPTIONS']) class OrgProducts(Resource): \"\"\"Resource for managing product", "required by applicable law or agreed to in writing, software", "= request.get_json() valid_format, errors = schema_utils.validate(request_json, 'org_product_subscription') if not valid_format:", "= {'message': 'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED", "{'message': schema_utils.serialize(errors)}, http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "Resource, cors from auth_api import status as http_status from auth_api.exceptions", "Tracer from auth_api.utils.roles import Role from auth_api.utils.util import cors_preflight API", "limitations under the License. \"\"\"API endpoints for managing an Org", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "{'message': 'Not authorized to perform this action'}, \\ http_status.HTTP_401_UNAUTHORIZED else:", "License is distributed on an 'AS IS' BASIS, # WITHOUT", "import request from flask_restplus import Namespace, Resource, cors from auth_api", "product subscriptions.\"\"\" @staticmethod @TRACER.trace() @cors.crossdomain(origin='*') @_JWT.has_one_of_roles([Role.STAFF_CREATE_ACCOUNTS.value]) def post(org_id): \"\"\"Post a", "subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None: response, status", "http_status.HTTP_400_BAD_REQUEST try: subscriptions = ProductService.create_product_subscription(org_id, request_json) if subscriptions is None:", "TRACER = Tracer.get_instance() _JWT = JWTWrapper.get_instance() @cors_preflight('GET,POST,OPTIONS') @API.route('', methods=['GET', 'POST',", "subscriptions is None: response, status = {'message': 'Not authorized to", "'License'); # you may not use this file except in", "distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR" ]
[ "all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), }", "pending app queryset, along # with a count of how", "dictionary with the three status codes # we'd want to", "from django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models", "import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor", "import BaseCommand from django.db.models import Q from TWLight.applications.models import Application", ").count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0])", "Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But", "*args, **options): # This is not DRY. Originally, this pulled", "Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count", "with the three status codes # we'd want to send", "# for partners with a status of AVAILABLE. all_apps =", "request object. So, we did a copy/paste. # We're actually", "& Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False,", "**options): # This is not DRY. Originally, this pulled the", "app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter(", "of coordinators from the pending app queryset, along # with", "\"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()): try: #", "\"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()):", "a dictionary with the three status codes # we'd want", "in list(coordinators.items()): try: # We create a dictionary with the", ").count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0],", "import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args,", "# This is not DRY. Originally, this pulled the queryset", "Command(BaseCommand): def handle(self, *args, **options): # This is not DRY.", "or QUESTION # or APPROVED, and their corresponding user preferences", "# Only bother with the signal if we have a", "the signal if we have a coordinator email. if coordinator[1]:", "a status of PENDING or QUESTION # or APPROVED, and", "try: # We create a dictionary with the three status", "| Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True )", "the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects", "is not DRY. Originally, this pulled the queryset from #", "want to send emails for, and their corresponding # counts.", "all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in", "how many total pending apps they have coordinators = Counter(", "Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0])", "their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING,", "class Command(BaseCommand): def handle(self, *args, **options): # This is not", "they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", )", "# counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(),", "TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__)", "with the signal if we have a coordinator email. if", "a request object. So, we did a copy/paste. # We're", "with a status of AVAILABLE. all_apps = ( Application.objects.filter( Q(", "& Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") )", "if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__,", "with a status of PENDING or QUESTION # or APPROVED,", "import Q from TWLight.applications.models import Application from TWLight.resources.models import Partner", "now expects a request object. So, we did a copy/paste.", ").count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {}", "from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger =", "from the pending app queryset, along # with a count", "that now expects a request object. So, we did a", "queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a", "coordinator, count in list(coordinators.items()): try: # We create a dictionary", "and their corresponding user preferences being True # for partners", "for coordinator, count in list(coordinators.items()): try: # We create a", "this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that", "BaseCommand from django.db.models import Q from TWLight.applications.models import Application from", "True # for partners with a status of AVAILABLE. all_apps", "partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\",", "status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info(", ") break # Only bother with the signal if we", "along # with a count of how many total pending", "Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(),", "logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): #", "status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor", "a count of how many total pending apps they have", "of PENDING or QUESTION # or APPROVED, and their corresponding", "We're actually getting apps with a status of PENDING or", "Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options):", "count in list(coordinators.items()): try: # We create a dictionary with", "django.db.models import Q from TWLight.applications.models import Application from TWLight.resources.models import", "& Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q(", "getting apps with a status of PENDING or QUESTION #", "preferences being True # for partners with a status of", "status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter(", "bother with the signal if we have a coordinator email.", "= Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not exist;", "from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def", "list(coordinators.items()): try: # We create a dictionary with the three", "logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break #", ".order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict of coordinators", "from django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models", "= ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q(", "logging from collections import Counter from django.core.management.base import BaseCommand from", "Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from", "| Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\")", "of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) &", ") ) for coordinator, count in list(coordinators.items()): try: # We", "the pending app queryset, along # with a count of", "to send emails for, and their corresponding # counts. app_status_and_count", "pending apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\",", "{ Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0],", "apps with a status of PENDING or QUESTION # or", "\"partner\", \"date_created\") ) # A deduplicated dict of coordinators from", "coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username, coordinator_email=coordinator[1], coordinator_lang=coordinator[2],", "queryset, along # with a count of how many total", "partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A", "not exist; skipping.\".format(coordinator[0]) ) break # Only bother with the", "= logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This", "Counter from django.core.management.base import BaseCommand from django.db.models import Q from", "we'd want to send emails for, and their corresponding #", ") & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE],", "have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username,", "does not exist; skipping.\".format(coordinator[0]) ) break # Only bother with", "DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). #", "a copy/paste. # We're actually getting apps with a status", "emails for, and their corresponding # counts. app_status_and_count = {", "partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED),", "We create a dictionary with the three status codes #", "Only bother with the signal if we have a coordinator", "Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) &", "Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) #", "Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) &", ") for coordinator, count in list(coordinators.items()): try: # We create", "handle(self, *args, **options): # This is not DRY. Originally, this", "Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break", "collections import Counter from django.core.management.base import BaseCommand from django.db.models import", "we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count,", "So, we did a copy/paste. # We're actually getting apps", "corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0],", "status of PENDING or QUESTION # or APPROVED, and their", "Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, )", "copy/paste. # We're actually getting apps with a status of", "status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True )", "all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED:", "break # Only bother with the signal if we have", "user preferences being True # for partners with a status", "Partner from TWLight.applications.signals import Reminder from TWLight.users.models import Editor logger", "have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) )", "not DRY. Originally, this pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset().", "deduplicated dict of coordinators from the pending app queryset, along", ") & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) |", "all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist:", "Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True )", "from TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals", "TWLight.applications.models import Application from TWLight.resources.models import Partner from TWLight.applications.signals import", "import Application from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder", "( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True", "Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except", "skipping.\".format(coordinator[0]) ) break # Only bother with the signal if", "or APPROVED, and their corresponding user preferences being True #", "partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION)", "from TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models", "app queryset, along # with a count of how many", "create a dictionary with the three status codes # we'd", "# or APPROVED, and their corresponding user preferences being True", "send emails for, and their corresponding # counts. app_status_and_count =", "= { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION,", "we did a copy/paste. # We're actually getting apps with", "\"Editor {} does not exist; skipping.\".format(coordinator[0]) ) break # Only", "APPROVED, and their corresponding user preferences being True # for", "for partners with a status of AVAILABLE. all_apps = (", "being True # for partners with a status of AVAILABLE.", "from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request", "\"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator, count in list(coordinators.items()): try:", "This is not DRY. Originally, this pulled the queryset from", "{} does not exist; skipping.\".format(coordinator[0]) ) break # Only bother", "counts. app_status_and_count = { Application.PENDING: all_apps.filter( status=Application.PENDING, partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION:", "editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does not", "# But that now expects a request object. So, we", "Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand):", "TWLight.resources.models import Partner from TWLight.applications.signals import Reminder from TWLight.users.models import", "def handle(self, *args, **options): # This is not DRY. Originally,", "did a copy/paste. # We're actually getting apps with a", "QUESTION # or APPROVED, and their corresponding user preferences being", "partner__coordinator__editor=coordinator[0], ).count(), } editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor", "django.core.management.base import BaseCommand from django.db.models import Q from TWLight.applications.models import", "except Editor.DoesNotExist: logger.info( \"Editor {} does not exist; skipping.\".format(coordinator[0]) )", "But that now expects a request object. So, we did", "pulled the queryset from # TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now", "for, and their corresponding # counts. app_status_and_count = { Application.PENDING:", "and their corresponding # counts. app_status_and_count = { Application.PENDING: all_apps.filter(", "# we'd want to send emails for, and their corresponding", "corresponding user preferences being True # for partners with a", "Q from TWLight.applications.models import Application from TWLight.resources.models import Partner from", "TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object. So,", "\"date_created\") ) # A deduplicated dict of coordinators from the", "actually getting apps with a status of PENDING or QUESTION", "AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING)", ") # A deduplicated dict of coordinators from the pending", "count of how many total pending apps they have coordinators", "# TWLight.applications.views.ListApplicationsView.get_queryset(). # But that now expects a request object.", "partner__coordinator__editor=coordinator[0], ).count(), Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED,", "Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True ) & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\",", "import logging from collections import Counter from django.core.management.base import BaseCommand", ") .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict", "a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username, coordinator_email=coordinator[1],", "from collections import Counter from django.core.management.base import BaseCommand from django.db.models", "# with a count of how many total pending apps", "a status of AVAILABLE. all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True", "logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): # This is", ") & Q(status=Application.APPROVED), partner__status__in=[Partner.AVAILABLE], editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\")", "TWLight.users.models import Editor logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self,", ".exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated dict of", "object. So, we did a copy/paste. # We're actually getting", "of how many total pending apps they have coordinators =", "= Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for coordinator,", "Application.QUESTION: all_apps.filter( status=Application.QUESTION, partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(),", "partner__coordinator__editor=coordinator[0], ).count(), Application.APPROVED: all_apps.filter( status=Application.APPROVED, partner__coordinator__editor=coordinator[0], ).count(), } editor =", "import Counter from django.core.management.base import BaseCommand from django.db.models import Q", "# We're actually getting apps with a status of PENDING", "} editor = Editor.objects.get(id=coordinator[0]) except Editor.DoesNotExist: logger.info( \"Editor {} does", "coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\", ) ) for", "Q(status=Application.PENDING) | Q( partner__coordinator__editor__user__userprofile__discussion_app_reminders=True ) & Q(status=Application.QUESTION) | Q( partner__coordinator__editor__user__userprofile__approved_app_reminders=True", "coordinators from the pending app queryset, along # with a", "their corresponding user preferences being True # for partners with", "PENDING or QUESTION # or APPROVED, and their corresponding user", "codes # we'd want to send emails for, and their", "A deduplicated dict of coordinators from the pending app queryset,", "# We create a dictionary with the three status codes", "email. if coordinator[1]: Reminder.coordinator_reminder.send( sender=self.__class__, app_status_and_count=app_status_and_count, coordinator_wp_username=editor.wp_username, coordinator_email=coordinator[1], coordinator_lang=coordinator[2], )", "signal if we have a coordinator email. if coordinator[1]: Reminder.coordinator_reminder.send(", "all_apps = ( Application.objects.filter( Q( partner__coordinator__editor__user__userprofile__pending_app_reminders=True ) & Q(status=Application.PENDING) |", "the three status codes # we'd want to send emails", "partners with a status of AVAILABLE. all_apps = ( Application.objects.filter(", "apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\", \"partner__coordinator__email\", \"partner__coordinator__editor__user__userprofile__lang\",", "import Reminder from TWLight.users.models import Editor logger = logging.getLogger(__name__) class", "many total pending apps they have coordinators = Counter( all_apps.values_list(", "total pending apps they have coordinators = Counter( all_apps.values_list( \"partner__coordinator__editor\",", "three status codes # we'd want to send emails for,", "with a count of how many total pending apps they", "# A deduplicated dict of coordinators from the pending app", "dict of coordinators from the pending app queryset, along #", "status codes # we'd want to send emails for, and", "expects a request object. So, we did a copy/paste. #", "editor__isnull=False, ) .exclude(editor__user__groups__name=\"restricted\") .order_by(\"status\", \"partner\", \"date_created\") ) # A deduplicated", "exist; skipping.\".format(coordinator[0]) ) break # Only bother with the signal" ]
[ "2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__()", "0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon =", "isotropic vectors is taken from GNU Scientific Library LOOP =", "photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\" A source", "self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] =", "sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05,", "np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction", "A source where photons generated in a plane are focused", "= np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) #", "return photon class CylindricalSource(object): \"\"\" A source for photons emitted", "If not, see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations", "class SimpleSource(object): \"\"\"A light source that will generate photons of", "spectrum self.wavelength = wavelength self.shape = Cylinder(radius = radius, length", "discrete angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum =", "= np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.))", "focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] =", "as tf from Trace import Photon from Geometry import Box,", "translation_matrix, rotation_matrix import external.transformations as tf from Trace import Photon", "np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will generate photons", "\"LensSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "are focused on a line with space tolerance given by", "* x y = a * y return np.array([x,y,z]) class", "in the GLOBAL FRAME. # i.e. this is passed directly", "0.) # Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction", "to the plane normal and aligned with the z-axis. \"\"\"", "Library LOOP = True while LOOP: x = -1. +", "__init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum =", "__init__(self, spectrum = None, wavelength = 555, radius = 1,", "length) self.radius = radius self.length = length self.throw = 0", "\"\"\" A point source that emits randomly in solid angle", "self.focussize = focussize self.throw = 0 self.source_id = \"LensSource_\" +", "= 2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__()", "wavelength assert polarisation != None, \"Polarisation of the Laser is", "# # pvtrace is distributed in the hope that it", "transform_point(local_center, self.shape.transform) # Direction of emission (no need to transform", "= wavelength assert polarisation != None, \"Polarisation of the Laser", "point = transform_point(self.center, transform) photon.direction = direction photon.position = point", "from GNU Scientific Library LOOP = True while LOOP: x", "* np.random.uniform() s = x**2 + y**2 if s <=", "self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self):", "under the terms of the GNU General Public License as", "1 return photon class PlanarSource(object): \"\"\"A box that emits photons", "of the plane in the GLOBAL FRAME. # i.e. this", "super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin =", "light source that will generate photons of a single colour,", "= self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y", "direction/modulus # Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "random direction and position inside a cylinder(radius, length) \"\"\" def", "return photon class LensSourceAngle(object): \"\"\" A source where photons generated", "photon.direction = direction photon.position = point if self.spectrum != None:", "np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength", "= np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0]", "self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1],", "self.direction = direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw", "= self.throw + 1 return photon class Laser(object): \"\"\"A light", "the GNU General Public License # along with this program.", "by variable \"focussize\". The focus line should be perpendicular to", "self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon", "= np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point =", "True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "= self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y", "or # (at your option) any later version. # #", "np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint - photon.position modulus", "local_point = (x, y, 0.) # Transform the direciton photon.position", "in it's local frame x = np.random.uniform(0., self.length) y =", "= \"PointSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "is's direction self.direction = direction self.throw = 0 self.source_id =", "self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon()", "inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta)", "np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length)", "self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self,", "= position self.direction = direction self.wavelength = wavelength self.use_random_polarisation =", "# GNU General Public License for more details. # #", "linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin =", "self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self):", "photon.source = self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active", "aligned with the z-axis. \"\"\" def __init__(self, spectrum = None,", "LensSourceAngle(object): \"\"\" A source where photons generated in a plane", "+ str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis):", "be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x =", "= -1. + 2. * np.random.uniform() s = x**2 +", "-1. + 2. * s a = 2 * np.sqrt(1", "translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def", "LensSource(object): \"\"\" A source where photons generated in a plane", "= Photon() photon.source = self.source_id photon.id = self.throw self.throw =", "photon to set is's direction self.direction = direction self.throw =", "= (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum", "= self.throw self.throw = self.throw + 1 phi = np.random.uniform(self.phimin,", "tolerance given by variable \"focussize\". The focus line should be", "= r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position =", "else: photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\" A", "position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position", "return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will generate", "tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction photon.position =", "Create a point which is on the surface of the", "= \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self,", "self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id", "plane in it's local frame x = np.random.uniform(0., self.length) y", "self.wavelength return photon class CylindricalSource(object): \"\"\" A source for photons", "else: photon.wavelength = self.wavelength photon.active = True return photon class", "the surface of the finite plane in it's local frame", "np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction focuspoint =", "point source that emits at discrete angles theta(i) and phi(i)", "normal and aligned with the z-axis. \"\"\" def __init__(self, spectrum", "around xy-plane, the transform from +z to the direction of", "0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon =", "General Public License for more details. # # You should", "return photon class PlanarSource(object): \"\"\"A box that emits photons from", "if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength =", "def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon =", "center = (0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin", "def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis))", "wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin =", "of the Laser is not set.\" self.polarisation = np.array(polarisation) self.throw", "A PARTICULAR PURPOSE. See the # GNU General Public License", "any later version. # # pvtrace is distributed in the", "self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw", "+ 2. * s a = 2 * np.sqrt(1 -", "self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def", "= self.throw self.throw = self.throw + 1 # Create a", "randomly in solid angle specified by phimin, ..., thetamax \"\"\"", "self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta)", "Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction)", "point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm", "the photon vec = random_spherecial_vector() vec[2] = 0. vec =", "photons of a single colour, direction and position.\"\"\" def __init__(self,", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation", "np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z =", "option) any later version. # # pvtrace is distributed in", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "= 0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon", "def __init__(self, spectrum = None, wavelength = 555, radius =", "0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation))", "self.throw = self.throw + 1 return photon class Laser(object): \"\"\"A", "version. # # pvtrace is distributed in the hope that", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "If use_polarisation is set generate a random polarisation vector of", "= 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation", "self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def", "from external.transformations import translation_matrix, rotation_matrix import external.transformations as tf from", "directly to the photon to set is's direction self.direction =", "+ str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis):", "+ 1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1)", "= np.array(self.direction) photon.active = True photon.wavelength = self.wavelength # If", "a random direction and position inside a cylinder(radius, length) \"\"\"", "wavelength = 555, radius = 1, length = 10): super(CylindricalSource,", "self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True", "= spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length", "polarisation != None, \"Polarisation of the Laser is not set.\"", "frame x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point", "of the GNU General Public License as published by #", "= 0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon", "= None photon.id = self.throw self.throw = self.throw + 1", "import translation_matrix, rotation_matrix import external.transformations as tf from Trace import", "= None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0,", "= photon.position[2] + boost direction = focuspoint - photon.position modulus", "= (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum", "with the z-axis. For this lense an additional z-boost is", "photon.id = self.throw self.throw = self.throw + 1 phi =", "can redistribute it and/or modify # it under the terms", "y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform", "photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] =", "(x, y, 0.) # Transform the direciton photon.position = transform_point(local_point,", "direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction =", "of photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "self.throw = 0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self):", "def photon(self): photon = Photon() photon.source = self.source_id photon.position =", "np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y", "= self.wavelength # If use_polarisation is set generate a random", "R) else: photon.polarisation = None photon.id = self.throw self.throw =", "planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize", "self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin,", "is passed directly to the photon to set is's direction", "given by variable \"focussize\". The focus line should be perpendicular", "direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0", "as published by # the Free Software Foundation; either version", "photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength", "phimax self.thetamin = thetamin self.thetamax = thetamax self.throw = 0", "For this lense an additional z-boost is added (Angle of", "= (x,y,z) photon.direction = local_direction # Set wavelength of photon", "(-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin", "single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555,", "= 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum =", "= np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction =", "solid angle specified by phimin, ..., thetamax \"\"\" def __init__(self,", "\"\"\" def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0),", "True photon.wavelength = self.wavelength # If use_polarisation is set generate", "= self.throw + 1 # Position of emission phi =", "+ 2. * np.random.uniform() y = -1. + 2. *", "= norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R)", "\"\"\"A box that emits photons from the top surface (normal),", "= width # direction is the direction that photons are", "np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0]", "= 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1),", "np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta)", "= self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw =", "self.width = width # direction is the direction that photons", "= np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position =", "0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum", "program. If not, see <http://www.gnu.org/licenses/>. import numpy as np from", "angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source", "= intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin else:", "License for more details. # # You should have received", "the plane normal and aligned with the z-axis. For this", "= self.throw self.throw = self.throw + 1 # Position of", "Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum", "direction self.direction = direction self.throw = 0 self.source_id = \"PlanarSource_\"", "= \"LaserSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "additional z-boost is added (Angle of incidence in z-direction). \"\"\"", "a random polarisation vector of the photon if self.use_random_polarisation: #", "focussize self.throw = 0 self.source_id = \"LensSource_\" + str(id(self)) def", "planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum =", "z-axis. \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x =", "the License, or # (at your option) any later version.", "def __init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1),", "= np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction =", "photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength #", "PARTICULAR PURPOSE. See the # GNU General Public License for", "1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost", "self.spectrum = spectrum self.wavelength = wavelength self.center = center self.phimin", "str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.position", "focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle,", "self.thetamax = thetamax self.spacing = spacing self.throw = 0 self.source_id", "position self.direction = direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation", "str(id(self)) def photon(self): photon = Photon() photon.id = self.throw self.throw", "transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True if self.spectrum", "= phimax self.thetamin = thetamin self.thetamax = thetamax self.throw =", "of a single colour, direction and position.\"\"\" def __init__(self, position=[0,0,0],", "emits photons from the top surface (normal), sampled from the", "z-boost is added (Angle of incidence in z-direction). \"\"\" def", "terms of the GNU General Public License as published by", "modify # it under the terms of the GNU General", "class PlanarSource(object): \"\"\"A box that emits photons from the top", "self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id", "colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None):", "= \"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon() photon.id", "generate a random polarisation vector of the photon if self.use_random_polarisation:", "self.use_random_polarisation: # Randomise rotation angle around xy-plane, the transform from", "= np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert polarisation", "details. # # You should have received a copy of", "cylinder(radius, length) \"\"\" def __init__(self, spectrum = None, wavelength =", "[0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None photon.id", "self.spectrum = spectrum self.wavelength = wavelength self.shape = Cylinder(radius =", "inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum = None,", "photon.wavelength = self.wavelength # Further initialisation photon.active = True return", "= wavelength self.plane = FinitePlane(length=length, width=width) self.length = length self.width", "perpendicular to the plane normal and aligned with the z-axis.", "photon class CylindricalSource(object): \"\"\" A source for photons emitted in", "= \"LensSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "top surface (normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None,", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\"", "plane in the GLOBAL FRAME. # i.e. this is passed", "if s <= 1.0: LOOP = False z = -1.", "emission (no need to transform if meant to be isotropic)", "self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" +", "set generate a random polarisation vector of the photon if", "Photon() photon.id = self.throw self.throw = self.throw + 1 #", "if self.thetamin == self.thetamax: theta = self.thetamin else: theta =", "= -1. + 2. * s a = 2 *", "transform_point(self.center, transform) photon.direction = direction photon.position = point if self.spectrum", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True", "self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self):", "photon.id = self.throw self.throw = self.throw + 1 return photon", "str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id photon.id", "set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\"", "photon.direction = self.direction photon.active = True if self.spectrum != None:", "spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize =", "need to transform if meant to be isotropic) phi =", "a cylinder(radius, length) \"\"\" def __init__(self, spectrum = None, wavelength", "Software Foundation; either version 3 of the License, or #", "= np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing", "+ 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1])", "True return photon class PointSource(object): \"\"\" A point source that", "z-axis. For this lense an additional z-boost is added (Angle", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength #", "wavelength = 555, center = (0.,0.,0.), phimin = 0, phimax", "= transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True if", "y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position", "= self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta =", "None photon.id = self.throw self.throw = self.throw + 1 return", "= focussize self.throw = 0 self.source_id = \"LensSource_\" + str(id(self))", "= np.array(linedirection) self.focussize = focussize self.angle = angle self.throw =", "received a copy of the GNU General Public License #", "= self.throw self.throw = self.throw + 1 intphi = np.random.randint(1,", "np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction # Set wavelength", "= False z = -1. + 2. * s a", "self.throw = self.throw + 1 # Create a point which", "y = np.random.uniform(0., self.width) local_point = (x, y, 0.) #", "= 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self): photon", "x y = a * y return np.array([x,y,z]) class SimpleSource(object):", "np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id = \"LensSource_\"", "return photon class LensSource(object): \"\"\" A source where photons generated", "555, radius = 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum", "np.array(direction) self.wavelength = wavelength assert polarisation != None, \"Polarisation of", "along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy", "np.sqrt(1 - s) x = a * x y =", "= 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum", "and phi(i) \"\"\" def __init__(self, spectrum = None, wavelength =", "See the # GNU General Public License for more details.", "self.position = position self.direction = direction self.wavelength = wavelength self.use_random_polarisation", "self.throw self.throw = self.throw + 1 # Create a point", "photon.active = True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "with the z-axis. \"\"\" def __init__(self, spectrum = None, wavelength", "boost photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0]", "self.wavelength photon.active = True return photon class RadialSource(object): \"\"\" A", "phi(i) \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "line should be perpendicular to the plane normal and aligned", "= np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "use_polarisation is set generate a random polarisation vector of the", "Materials import Spectrum def random_spherecial_vector(): # This method of calculating", "length = length) self.radius = radius self.length = length self.throw", "vector of the photon if self.use_random_polarisation: # Randomise rotation angle", "the plane normal and aligned with the z-axis. \"\"\" def", "i.e. this is passed directly to the photon to set", "= 0 self.source_id = \"PlanarSource_\" + str(id(self)) def translate(self, translation):", "= (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of emission", "the GLOBAL FRAME. # i.e. this is passed directly to", "else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\" A", "should be perpendicular to the plane normal and aligned with", "the Free Software Foundation; either version 3 of the License,", "that it will be useful, # but WITHOUT ANY WARRANTY;", "Photon from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment,", "focused on a line with space tolerance given by variable", "= (x, y, 0.) # Transform the direciton photon.position =", "photon.direction = direction/modulus # Wavelength if self.spectrum != None: photon.wavelength", "0, focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)):", "= self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction", "spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center", "on a line with space tolerance given by variable \"focussize\".", "= True photon.wavelength = self.wavelength # If use_polarisation is set", "either version 3 of the License, or # (at your", "self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y =", "the z-axis. For this lense an additional z-boost is added", "photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw", "# Create a point which is on the surface of", "Cylinder(radius = radius, length = length) self.radius = radius self.length", "import numpy as np from external.transformations import translation_matrix, rotation_matrix import", "radius self.length = length self.throw = 0 self.source_id = \"CylindricalSource_\"", "* np.random.uniform() y = -1. + 2. * np.random.uniform() s", "= np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation =", "a line with space tolerance given by variable \"focussize\". The", "self.throw + 1 # Position of emission phi = np.random.uniform(0.,", "self.polarisation = np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" +", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation photon.active", "class PointSource(object): \"\"\" A point source that emits randomly in", "more details. # # You should have received a copy", "LOOP = False z = -1. + 2. * s", "from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05):", "direction self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self)) def", "= \"RadialSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "\"\"\" A source for photons emitted in a random direction", "1 return photon class Laser(object): \"\"\"A light source that will", "\"Polarisation of the Laser is not set.\" self.polarisation = np.array(polarisation)", "np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] +", "0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi):", "y**2 if s <= 1.0: LOOP = False z =", "length self.width = width # direction is the direction that", "x**2 + y**2 if s <= 1.0: LOOP = False", "be useful, # but WITHOUT ANY WARRANTY; without even the", "y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) #", "linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin = (-1,-1,-1),", "photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active = True", "angle self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def", "self.radius = radius self.length = length self.throw = 0 self.source_id", "self.throw + 1 # Create a point which is on", "and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__()", "Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle)", "not set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id =", "1 # Create a point which is on the surface", "vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec,", "of emission (no need to transform if meant to be", "else: photon.wavelength = self.wavelength # Further initialisation photon.active = True", "phimax = 2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource,", "x = a * x y = a * y", "-1. + 2. * np.random.uniform() s = x**2 + y**2", "\"LensSourceAngle_\" + str(id(self)) def photon(self): photon = Photon() photon.id =", "x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z", "self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert", "+ 1 return photon class Laser(object): \"\"\"A light source that", "source that emits randomly in solid angle specified by phimin,", "phimin = 0, phimax = 2*np.pi, thetamin = 0, thetamax", "rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None", "self.wavelength photon.polarisation = self.polarisation photon.id = self.throw self.throw = self.throw", "focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize)", "= r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center =", "axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source =", "self.wavelength # If use_polarisation is set generate a random polarisation", "photon.direction = local_direction # Set wavelength of photon if self.spectrum", "= np.array(direction) self.wavelength = wavelength assert polarisation != None, \"Polarisation", "is set generate a random polarisation vector of the photon", "self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle", "= y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z))", "vec = random_spherecial_vector() vec[2] = 0. vec = norm(vec) R", "# along with this program. If not, see <http://www.gnu.org/licenses/>. import", "spacing self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self)) def", "direction that photons are fired out of the plane in", "z = np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction #", "length self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def", "= use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self))", "np.random.uniform(0., self.width) local_point = (x, y, 0.) # Transform the", "# If use_polarisation is set generate a random polarisation vector", "555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0, planeorigin", "else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta)", "= angle self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self))", "= photon.position[2] direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5", "photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction", "str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle,", "focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost", "position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction", "that emits photons from the top surface (normal), sampled from", "(x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction =", "1.0: LOOP = False z = -1. + 2. *", "self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent", "z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction", "is free software; you can redistribute it and/or modify #", "= np.cos(theta) local_direction = (x,y,z) photon.direction = local_direction # Set", "a plane are focused on a line with space tolerance", "from the top surface (normal), sampled from the spectrum.\"\"\" def", "planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection)", "= self.wavelength # Further initialisation photon.active = True return photon", "= self.direction photon.active = True if self.spectrum != None: photon.wavelength", "+ np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2]", "self.phimin = phimin self.phimax = phimax self.thetamin = thetamin self.thetamax", "self.thetamin = thetamin self.thetamax = thetamax self.spacing = spacing self.throw", "np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0))", "polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength", "initialisation photon.active = True return photon class PointSource(object): \"\"\" A", "+ 1 # Position of emission phi = np.random.uniform(0., 2*np.pi)", "rotation angle around xy-plane, the transform from +z to the", "direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction =", "wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\"", "= focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus", "# Position of emission phi = np.random.uniform(0., 2*np.pi) r =", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y", "= x**2 + y**2 if s <= 1.0: LOOP =", "R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation", "photon(self): photon = Photon() photon.id = self.throw self.throw = self.throw", "this program. If not, see <http://www.gnu.org/licenses/>. import numpy as np", "inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin ==", "and/or modify # it under the terms of the GNU", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active =", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\"", "norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else:", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSource(object):", "meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi)", "= 2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource,", "y = a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A", "CylindricalSource(object): \"\"\" A source for photons emitted in a random", "= np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point = (x,", "self.direction photon.active = True if self.spectrum != None: photon.wavelength =", "planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum =", "str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle,", "x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position", "= self.wavelength return photon class CylindricalSource(object): \"\"\" A source for", "it and/or modify # it under the terms of the", "transform from +z to the direction of the photon vec", "to the direction of the photon vec = random_spherecial_vector() vec[2]", "focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus #", "(direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum != None:", "direction and position inside a cylinder(radius, length) \"\"\" def __init__(self,", "phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing = spacing", "self.throw self.throw = self.throw + 1 # Position x =", "length) \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "by phimin, ..., thetamax \"\"\" def __init__(self, spectrum = None,", "self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize", "thetamin self.thetamax = thetamax self.spacing = spacing self.throw = 0", "it will be useful, # but WITHOUT ANY WARRANTY; without", "and position inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum", "the photon to set is's direction self.direction = direction self.throw", "radius = 1, length = 10): super(CylindricalSource, self).__init__() self.spectrum =", "= None, wavelength = 555, center = (0.,0.,0.), phimin =", "angle = 0, focussize = 0, planeorigin = (-1,-1,-1), planeextent", "= 0, phimax = 2*np.pi, thetamin = 0, thetamax =", "source for photons emitted in a random direction and position", "translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self):", "generate photons of a single colour, direction and position.\"\"\" def", "self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint -", "= 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize = 0,", "# Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "free software; you can redistribute it and/or modify # it", "later version. # # pvtrace is distributed in the hope", "self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon", "angle specified by phimin, ..., thetamax \"\"\" def __init__(self, spectrum", "0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation =", "# it under the terms of the GNU General Public", "photon.wavelength = self.wavelength photon.active = True return photon class RadialSource(object):", "from Trace import Photon from Geometry import Box, Cylinder, FinitePlane,", "is added (Angle of incidence in z-direction). \"\"\" def __init__(self,", "angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum = None,", "class RadialSource(object): \"\"\" A point source that emits at discrete", "= np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost", "- boost photon.position = np.array((x,y,z)) # Direction focuspoint = np.array((0.,0.,0.))", "of the License, or # (at your option) any later", "= True if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "assert polarisation != None, \"Polarisation of the Laser is not", "= 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum", "def __init__(self, spectrum = None, wavelength = 555, center =", "direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser,", "hope that it will be useful, # but WITHOUT ANY", "= direction self.throw = 0 self.source_id = \"PlanarSource_\" + str(id(self))", "it under the terms of the GNU General Public License", "photons from the top surface (normal), sampled from the spectrum.\"\"\"", "self.throw = self.throw + 1 # Position of emission phi", "= np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z =", "to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x", "= (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "\"\"\" def __init__(self, spectrum = None, wavelength = 555, center", "self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x =", "are fired out of the plane in the GLOBAL FRAME.", "= radius, length = length) self.radius = radius self.length =", "= np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1]", "This method of calculating isotropic vectors is taken from GNU", "GNU General Public License # along with this program. If", "photon.position = point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon = Photon()", "photon class RadialSource(object): \"\"\" A point source that emits at", "..., thetamax \"\"\" def __init__(self, spectrum = None, wavelength =", "a = 2 * np.sqrt(1 - s) x = a", "the GNU General Public License as published by # the", "if self.use_random_polarisation: # Randomise rotation angle around xy-plane, the transform", "0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon =", "z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform)", "which is on the surface of the finite plane in", "= self.throw self.throw = self.throw + 1 return photon class", "* s a = 2 * np.sqrt(1 - s) x", "np.array(self.direction) photon.active = True photon.wavelength = self.wavelength # If use_polarisation", "transform_direction(vec, R) else: photon.polarisation = None photon.id = self.throw self.throw", "self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon = Photon()", "width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane", "self.source_id photon.id = self.throw self.throw = self.throw + 1 intphi", "self.spectrum = spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width)", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "self.wavelength = wavelength self.shape = Cylinder(radius = radius, length =", "def photon(self): photon = Photon() photon.source = self.source_id photon.id =", "Public License # along with this program. If not, see", "it's local frame x = np.random.uniform(0., self.length) y = np.random.uniform(0.,", "see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations import translation_matrix,", "the photon if self.use_random_polarisation: # Randomise rotation angle around xy-plane,", "General Public License as published by # the Free Software", "in a plane are focused on a line with space", "class LensSourceAngle(object): \"\"\" A source where photons generated in a", "method of calculating isotropic vectors is taken from GNU Scientific", "np.array(linedirection) self.focussize = focussize self.angle = angle self.throw = 0", "photon.id = self.throw self.throw = self.throw + 1 # Create", "+ 1 return photon class PlanarSource(object): \"\"\"A box that emits", "in a random direction and position inside a cylinder(radius, length)", "will be useful, # but WITHOUT ANY WARRANTY; without even", "= a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light", "spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent = planeextent", "photons emitted in a random direction and position inside a", "your option) any later version. # # pvtrace is distributed", "np.random.uniform() y = -1. + 2. * np.random.uniform() s =", "The focus line should be perpendicular to the plane normal", "plane are focused on a line with space tolerance given", "photon = Photon() photon.source = self.source_id photon.id = self.throw self.throw", "linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent =", "published by # the Free Software Foundation; either version 3", "Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2])", "boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position =", "= Cylinder(radius = radius, length = length) self.radius = radius", "boost direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction", "False z = -1. + 2. * s a =", "self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source = self.source_id", "return photon class Laser(object): \"\"\"A light source that will generate", "direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform)", "of calculating isotropic vectors is taken from GNU Scientific Library", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin = planeorigin", "transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector(): #", "self.throw self.throw = self.throw + 1 # Position of emission", "width # direction is the direction that photons are fired", "to the photon to set is's direction self.direction = direction", "= radius self.length = length self.throw = 0 self.source_id =", "direction photon.position = point if self.spectrum != None: photon.wavelength =", "fired out of the plane in the GLOBAL FRAME. #", "self.throw = self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta", "PURPOSE. See the # GNU General Public License for more", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further", "plane normal and aligned with the z-axis. \"\"\" def __init__(self,", "self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon = Photon()", "is the direction that photons are fired out of the", "FOR A PARTICULAR PURPOSE. See the # GNU General Public", "= 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__()", "self.length = length self.throw = 0 self.source_id = \"CylindricalSource_\" +", "if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta =", "self.throw self.throw = self.throw + 1 intphi = np.random.randint(1, self.spacing+1)", "photon(self): photon = Photon() photon.source = self.source_id photon.id = self.throw", "s = x**2 + y**2 if s <= 1.0: LOOP", "the # GNU General Public License for more details. #", "that photons are fired out of the plane in the", "+ 1 # Create a point which is on the", "theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z", "the direction of the photon vec = random_spherecial_vector() vec[2] =", "np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation = self.polarisation", "the transform from +z to the direction of the photon", "def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum", "Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1]", "2. * s a = 2 * np.sqrt(1 - s)", "SimpleSource(object): \"\"\"A light source that will generate photons of a", "self.linedirection = np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id", "that will generate photons of a single colour, direction and", "the top surface (normal), sampled from the spectrum.\"\"\" def __init__(self,", "class LensSource(object): \"\"\" A source where photons generated in a", "\"PlanarSource_\" + str(id(self)) def translate(self, translation): self.plane.append_transform(tf.translation_matrix(translation)) def rotate(self, angle,", "photon = Photon() photon.id = self.throw self.throw = self.throw +", "def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon =", "center self.phimin = phimin self.phimax = phimax self.thetamin = thetamin", "True return photon class RadialSource(object): \"\"\" A point source that", "return photon class RadialSource(object): \"\"\" A point source that emits", "None, \"Polarisation of the Laser is not set.\" self.polarisation =", "local frame x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width)", "= transform_point(self.center, transform) photon.direction = direction photon.position = point if", "= self.wavelength return photon class LensSourceAngle(object): \"\"\" A source where", "for more details. # # You should have received a", "focuspoint[2] = photon.position[2] direction = focuspoint - photon.position modulus =", "np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta)", "= np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax:", "redistribute it and/or modify # it under the terms of", "PlanarSource(object): \"\"\"A box that emits photons from the top surface", "np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] +", "z = -1. + 2. * s a = 2", "import Spectrum def random_spherecial_vector(): # This method of calculating isotropic", "to the plane normal and aligned with the z-axis. For", "= spectrum self.wavelength = wavelength self.shape = Cylinder(radius = radius,", "= (0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin =", "r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center,", "GNU Scientific Library LOOP = True while LOOP: x =", "__init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle", "Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction", "direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource,", "local_direction # Set wavelength of photon if self.spectrum != None:", "linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)):", "True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id = self.throw", "+ np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction = focuspoint", "super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane =", "= Photon() photon.id = self.throw self.throw = self.throw + 1", "as np from external.transformations import translation_matrix, rotation_matrix import external.transformations as", "from Materials import Spectrum def random_spherecial_vector(): # This method of", "vec[2] = 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction, [0,0,1])", "self.shape = Cylinder(radius = radius, length = length) self.radius =", "of emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x", "2*np.pi, thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum", "photon if self.use_random_polarisation: # Randomise rotation angle around xy-plane, the", "= thetamin self.thetamax = thetamax self.throw = 0 self.source_id =", "is on the surface of the finite plane in it's", "= phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing =", "self.length) y = np.random.uniform(0., self.width) local_point = (x, y, 0.)", "= thetamin self.thetamax = thetamax self.spacing = spacing self.throw =", "np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta", "= None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0,", "= np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle =", "pvtrace is distributed in the hope that it will be", "self.angle = angle self.throw = 0 self.source_id = \"LensSourceAngle_\" +", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "source that will generate photons of a single colour, direction", "import external.transformations as tf from Trace import Photon from Geometry", "photon.position = transform_point(local_center, self.shape.transform) # Direction of emission (no need", "np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self)) def", "555, center = (0.,0.,0.), phimin = 0, phimax = 2*np.pi,", "self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self,", "FinitePlane(length=length, width=width) self.length = length self.width = width # direction", "(normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1),", "photon class PlanarSource(object): \"\"\"A box that emits photons from the", "that emits randomly in solid angle specified by phimin, ...,", "0 self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon =", "PointSource(object): \"\"\" A point source that emits randomly in solid", "photon.direction = np.array(self.direction) photon.active = True photon.wavelength = self.wavelength photon.polarisation", "= (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "+ boost direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5", "# i.e. this is passed directly to the photon to", "\"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "= np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y =", "self.throw self.throw = self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax)", "= thetamax self.spacing = spacing self.throw = 0 self.source_id =", "photon.source = self.source_id photon.id = self.throw self.throw = self.throw +", "the hope that it will be useful, # but WITHOUT", "and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__()", "self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength", "2 * np.sqrt(1 - s) x = a * x", "self.wavelength = wavelength assert polarisation != None, \"Polarisation of the", "Foundation; either version 3 of the License, or # (at", "passed directly to the photon to set is's direction self.direction", "\"\"\" A source where photons generated in a plane are", "<http://www.gnu.org/licenses/>. import numpy as np from external.transformations import translation_matrix, rotation_matrix", "= Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction =", "rotation_matrix import external.transformations as tf from Trace import Photon from", "= np.array(linedirection) self.focussize = focussize self.throw = 0 self.source_id =", "pvtrace is free software; you can redistribute it and/or modify", "self.wavelength = wavelength self.center = center self.phimin = phimin self.phimax", "wavelength self.plane = FinitePlane(length=length, width=width) self.length = length self.width =", "# direction is the direction that photons are fired out", "= direction photon.position = point if self.spectrum != None: photon.wavelength", "emitted in a random direction and position inside a cylinder(radius,", "= np.random.uniform(0., self.width) local_point = (x, y, 0.) # Transform", "!= None, \"Polarisation of the Laser is not set.\" self.polarisation", "transform if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi) theta", "a * y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source", "planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength =", "self.source_id photon.id = self.throw self.throw = self.throw + 1 phi", "transform) photon.direction = direction photon.position = point if self.spectrum !=", "photons generated in a plane are focused on a line", "= length self.width = width # direction is the direction", "= 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__()", "(Angle of incidence in z-direction). \"\"\" def __init__(self, spectrum =", "self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon = Photon()", "photon class Laser(object): \"\"\"A light source that will generate photons", "x = np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point =", "photon.position[2] direction = focuspoint - photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction", "wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength", "x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction", "source that emits at discrete angles theta(i) and phi(i) \"\"\"", "use_random_polarisation self.throw = 0 self.source_id = \"SimpleSource_\" + str(id(self)) def", "line with space tolerance given by variable \"focussize\". The focus", "y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that will", "external.transformations import translation_matrix, rotation_matrix import external.transformations as tf from Trace", "photon class PointSource(object): \"\"\" A point source that emits randomly", "copy of the GNU General Public License # along with", "photon.active = True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength # Further initialisation photon.active =", "random polarisation vector of the photon if self.use_random_polarisation: # Randomise", "the Laser is not set.\" self.polarisation = np.array(polarisation) self.throw =", "self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1,", "while LOOP: x = -1. + 2. * np.random.uniform() y", "radius, length = length) self.radius = radius self.length = length", "wavelength self.center = center self.phimin = phimin self.phimax = phimax", "to transform if meant to be isotropic) phi = np.random.uniform(0.,2*np.pi)", "with space tolerance given by variable \"focussize\". The focus line", "theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z", "= local_direction # Set wavelength of photon if self.spectrum !=", "None, wavelength = 555, radius = 1, length = 10):", "photon.active = True photon.wavelength = self.wavelength # If use_polarisation is", "self.direction = np.array(direction) self.wavelength = wavelength assert polarisation != None,", "Randomise rotation angle around xy-plane, the transform from +z to", "self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection", "np.random.uniform(0.,self.length) local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction", "Position of emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius)", "distributed in the hope that it will be useful, #", "True while LOOP: x = -1. + 2. * np.random.uniform()", "License, or # (at your option) any later version. #", "modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum", "s <= 1.0: LOOP = False z = -1. +", "self.throw = self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0])", "y = -1. + 2. * np.random.uniform() s = x**2", "self.source_id photon.id = self.throw self.throw = self.throw + 1 #", "self.linedirection = np.array(linedirection) self.focussize = focussize self.angle = angle self.throw", "# Direction of emission (no need to transform if meant", "thetamax \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "= np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction", "License # along with this program. If not, see <http://www.gnu.org/licenses/>.", "x = -1. + 2. * np.random.uniform() y = -1.", "thetamin self.thetamax = thetamax self.throw = 0 self.source_id = \"PointSource_\"", "* y return np.array([x,y,z]) class SimpleSource(object): \"\"\"A light source that", "np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] +", "and aligned with the z-axis. For this lense an additional", "at discrete angles theta(i) and phi(i) \"\"\" def __init__(self, spectrum", "You should have received a copy of the GNU General", "= self.throw + 1 # Create a point which is", "(-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength", "= center self.phimin = phimin self.phimax = phimax self.thetamin =", "self.throw = self.throw + 1 return photon class PlanarSource(object): \"\"\"A", "= 0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation):", "vectors is taken from GNU Scientific Library LOOP = True", "= spectrum self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent =", "z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint =", "emission phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x =", "taken from GNU Scientific Library LOOP = True while LOOP:", "self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length = length", "be perpendicular to the plane normal and aligned with the", "np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw = 0", "(x,y,z) photon.direction = local_direction # Set wavelength of photon if", "else: photon.polarisation = None photon.id = self.throw self.throw = self.throw", "0 self.source_id = \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation))", "= np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength =", "self.shape.transform) # Direction of emission (no need to transform if", "- photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength", "__init__(self, spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize", "focus line should be perpendicular to the plane normal and", "local_direction = (x,y,z) photon.direction = local_direction # Set wavelength of", "x = r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center", "lense an additional z-boost is added (Angle of incidence in", "\"\"\"A light source that will generate photons of a single", "photon.position modulus = (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "self.thetamin == self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing", "= self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2]", "\"LaserSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "Spectrum def random_spherecial_vector(): # This method of calculating isotropic vectors", "axis)) def photon(self): photon = Photon() photon.source = self.source_id photon.id", "photon.id = self.throw self.throw = self.throw + 1 intphi =", "random_spherecial_vector(): # This method of calculating isotropic vectors is taken", "(0.,0.,0.), phimin = 0, phimax = 2*np.pi, thetamin = 0,", "intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi =", "self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta =", "in z-direction). \"\"\" def __init__(self, spectrum = None, wavelength =", "# the Free Software Foundation; either version 3 of the", "thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength", "you can redistribute it and/or modify # it under the", "emits at discrete angles theta(i) and phi(i) \"\"\" def __init__(self,", "= self.throw + 1 intphi = np.random.randint(1, self.spacing+1) inttheta =", "self.wavelength return photon class LensSourceAngle(object): \"\"\" A source where photons", "= (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\"", "# You should have received a copy of the GNU", "= spectrum self.wavelength = wavelength self.center = center self.phimin =", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape = Cylinder(radius", "__init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position)", "= FinitePlane(length=length, width=width) self.length = length self.width = width #", "np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.angle = angle", "will generate photons of a single colour, direction and position.\"\"\"", "to set is's direction self.direction = direction self.throw = 0", "the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active", "y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) -", "= transform_direction(vec, R) else: photon.polarisation = None photon.id = self.throw", "np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z)", "that emits at discrete angles theta(i) and phi(i) \"\"\" def", "norm from Materials import Spectrum def random_spherecial_vector(): # This method", "photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class", "= 2 * np.sqrt(1 - s) x = a *", "self.wavelength return photon class LensSource(object): \"\"\" A source where photons", "source where photons generated in a plane are focused on", "10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape", "Direction of emission (no need to transform if meant to", "__init__(self, spectrum = None, wavelength = 555, center = (0.,0.,0.),", "= np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize = focussize self.throw =", "a * x y = a * y return np.array([x,y,z])", "= rotation_matrix_from_vector_alignment(self.direction, [0,0,1]) photon.polarisation = transform_direction(vec, R) else: photon.polarisation =", "= wavelength self.shape = Cylinder(radius = radius, length = length)", "self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.throw", "= transform_point(local_center, self.shape.transform) # Direction of emission (no need to", "def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis))", "numpy as np from external.transformations import translation_matrix, rotation_matrix import external.transformations", "should have received a copy of the GNU General Public", "variable \"focussize\". The focus line should be perpendicular to the", "+ y**2 if s <= 1.0: LOOP = False z", "external.transformations as tf from Trace import Photon from Geometry import", "= 0, focussize = 0, planeorigin = (-1,-1,-1), planeextent =", "def random_spherecial_vector(): # This method of calculating isotropic vectors is", "photon = Photon() photon.source = self.source_id photon.position = np.array(self.position) photon.direction", "= self.wavelength return photon class LensSource(object): \"\"\" A source where", "self.length = length self.width = width # direction is the", "photon class LensSourceAngle(object): \"\"\" A source where photons generated in", "isotropic) phi = np.random.uniform(0.,2*np.pi) theta = np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta)", "1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z", "super(SimpleSource, self).__init__() self.position = position self.direction = direction self.wavelength =", "= 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "phimin self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax", "of the GNU General Public License # along with this", "None, wavelength = 555, center = (0.,0.,0.), phimin = 0,", "self.wavelength # Further initialisation photon.active = True return photon class", "None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon", "of incidence in z-direction). \"\"\" def __init__(self, spectrum = None,", "LOOP = True while LOOP: x = -1. + 2.", "position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction", "self.throw + 1 return photon class Laser(object): \"\"\"A light source", "(-1,-1,-1), planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength", "= 0 self.source_id = \"PointSource_\" + str(id(self)) def photon(self): photon", "FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def", "wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction)", "= thetamax self.throw = 0 self.source_id = \"PointSource_\" + str(id(self))", "self.plane.transform) photon.direction = self.direction photon.active = True if self.spectrum !=", "Scientific Library LOOP = True while LOOP: x = -1.", "photon.polarisation = None photon.id = self.throw self.throw = self.throw +", "class CylindricalSource(object): \"\"\" A source for photons emitted in a", "y, 0.) # Transform the direciton photon.position = transform_point(local_point, self.plane.transform)", "# (at your option) any later version. # # pvtrace", "is taken from GNU Scientific Library LOOP = True while", "photon vec = random_spherecial_vector() vec[2] = 0. vec = norm(vec)", "# pvtrace is free software; you can redistribute it and/or", "spectrum = None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle =", "# Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost =", "the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource,", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class LensSourceAngle(object):", "None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize", "= \"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self,", "0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self): photon =", "= np.array(polarisation) self.throw = 0 self.source_id = \"LaserSource_\" + str(id(self))", "local_center = (x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of", "GNU General Public License as published by # the Free", "= -1. + 2. * np.random.uniform() y = -1. +", "# Further initialisation photon.active = True return photon class PointSource(object):", "0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon =", "thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength =", "aligned with the z-axis. For this lense an additional z-boost", "direction is the direction that photons are fired out of", "= True return photon class RadialSource(object): \"\"\" A point source", "+ str(id(self)) def photon(self): photon = Photon() photon.id = self.throw", "(no need to transform if meant to be isotropic) phi", "RadialSource(object): \"\"\" A point source that emits at discrete angles", "= np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z =", "focuspoint[2] = photon.position[2] + boost direction = focuspoint - photon.position", "rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector(): # This", "Wavelength if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength", "= focussize self.angle = angle self.throw = 0 self.source_id =", "super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.shape =", "thetamax self.spacing = spacing self.throw = 0 self.source_id = \"RadialSource_\"", "Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from", "== self.thetamax: theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x", "calculating isotropic vectors is taken from GNU Scientific Library LOOP", "np.random.uniform(-self.focussize,self.focussize) focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction", "phimax = 2*np.pi, thetamin = 0, thetamax = np.pi, spacing=20):", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "A point source that emits randomly in solid angle specified", "np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2])", "set is's direction self.direction = direction self.throw = 0 self.source_id", "Photon() photon.source = self.source_id photon.id = self.throw self.throw = self.throw", "point source that emits randomly in solid angle specified by", "self.wavelength = wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint", "wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), angle = 0, focussize =", "= 555, center = (0.,0.,0.), phimin = 0, phimax =", "np.random.uniform() s = x**2 + y**2 if s <= 1.0:", "not, see <http://www.gnu.org/licenses/>. import numpy as np from external.transformations import", "self.throw self.throw = self.throw + 1 return photon class PlanarSource(object):", "photons are fired out of the plane in the GLOBAL", "angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source", "width=width) self.length = length self.width = width # direction is", "1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x", "surface of the finite plane in it's local frame x", "= self.throw self.throw = self.throw + 1 # Position x", "np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength", "normal and aligned with the z-axis. For this lense an", "super(Laser, self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength =", "# Set wavelength of photon if self.spectrum != None: photon.wavelength", "__init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position", "# pvtrace is distributed in the hope that it will", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "on the surface of the finite plane in it's local", "License as published by # the Free Software Foundation; either", "General Public License # along with this program. If not,", "FRAME. # i.e. this is passed directly to the photon", "software; you can redistribute it and/or modify # it under", "spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__()", "= True return photon class PointSource(object): \"\"\" A point source", "s a = 2 * np.sqrt(1 - s) x =", "= None, wavelength = 555, radius = 1, length =", "np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y =", "Public License for more details. # # You should have", "class Laser(object): \"\"\"A light source that will generate photons of", "an additional z-boost is added (Angle of incidence in z-direction).", "self.throw = 0 self.source_id = \"LensSource_\" + str(id(self)) def photon(self):", "y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) #", "import Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials", "angle around xy-plane, the transform from +z to the direction", "rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon()", "0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength", "= planeextent self.linepoint = np.array(linepoint) self.linedirection = np.array(linedirection) self.focussize =", "= wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint =", "thetamin = 0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum", "intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin else: theta", "the terms of the GNU General Public License as published", "wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction = direction", "self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction =", "focussize = 0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource,", "focussize self.angle = angle self.throw = 0 self.source_id = \"LensSourceAngle_\"", "np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z)", "= wavelength self.use_random_polarisation = use_random_polarisation self.throw = 0 self.source_id =", "np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z))", "self.phimax = phimax self.thetamin = thetamin self.thetamax = thetamax self.spacing", "-1. + 2. * np.random.uniform() y = -1. + 2.", "point which is on the surface of the finite plane", "spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length, width=width) self.length =", "GLOBAL FRAME. # i.e. this is passed directly to the", "Further initialisation photon.active = True return photon class PointSource(object): \"\"\"", "colour, direction and position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False):", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "self.plane = FinitePlane(length=length, width=width) self.length = length self.width = width", "\"CylindricalSource_\" + str(id(self)) def translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle,", "planeextent = (-1,1,1)): super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength =", "super(RadialSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center =", "by # the Free Software Foundation; either version 3 of", "return photon class PointSource(object): \"\"\" A point source that emits", "thetamax self.throw = 0 self.source_id = \"PointSource_\" + str(id(self)) def", "= length) self.radius = radius self.length = length self.throw =", "= inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z =", "photon.id = self.throw self.throw = self.throw + 1 # Position", "focuspoint[1] = self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction =", "2. * np.random.uniform() s = x**2 + y**2 if s", "def photon(self): photon = Photon() photon.id = self.throw self.throw =", "= random_spherecial_vector() vec[2] = 0. vec = norm(vec) R =", "direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position = np.array(position) self.direction =", "A source for photons emitted in a random direction and", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return", "= 0 self.source_id = \"RadialSource_\" + str(id(self)) def photon(self): photon", "(x,y,z) photon.position = transform_point(local_center, self.shape.transform) # Direction of emission (no", "self.throw = self.throw + 1 phi = np.random.uniform(self.phimin, self.phimax) theta", "= np.sin(phi)*np.sin(theta) z = np.cos(theta) direction = (x,y,z) transform =", "space tolerance given by variable \"focussize\". The focus line should", "self.throw + 1 # Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y =", "length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength =", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center = center", "= self.throw + 1 return photon class PlanarSource(object): \"\"\"A box", "np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point = transform_point(self.center,", "2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi)", "a point which is on the surface of the finite", "# Position x = np.random.uniform(self.planeorigin[0],self.planeextent[0]) y = np.random.uniform(self.planeorigin[1],self.planeextent[1]) z =", "= np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta)", "s) x = a * x y = a *", "photon class LensSource(object): \"\"\" A source where photons generated in", "box that emits photons from the top surface (normal), sampled", "# This method of calculating isotropic vectors is taken from", "direction of the photon vec = random_spherecial_vector() vec[2] = 0.", "+ np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint - photon.position", "self.direction = direction self.throw = 0 self.source_id = \"PlanarSource_\" +", "version 3 of the License, or # (at your option)", "photon.position[2] + boost direction = focuspoint - photon.position modulus =", "axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon() photon.source =", "spectrum = None, wavelength = 555, radius = 1, length", "this is passed directly to the photon to set is's", "phi = np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi)", "spectrum = None, wavelength = 555, center = (0.,0.,0.), phimin", "super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center =", "theta = np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta)", "A point source that emits at discrete angles theta(i) and", "def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, polarisation=None): super(Laser, self).__init__() self.position =", "+ str(id(self)) def photon(self): photon = Photon() photon.source = self.source_id", "self).__init__() self.position = np.array(position) self.direction = np.array(direction) self.wavelength = wavelength", "np.random.uniform(self.planeorigin[1],self.planeextent[1]) boost = y*np.tan(self.angle) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position", "where photons generated in a plane are focused on a", "+ 2. * np.random.uniform() s = x**2 + y**2 if", "direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction = self.direction photon.active =", "* np.sqrt(1 - s) x = a * x y", "self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.plane = FinitePlane(length=length,", "= planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint) self.linedirection =", "plane normal and aligned with the z-axis. For this lense", "np.pi): super(PointSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.center", "= self.wavelength photon.active = True return photon class RadialSource(object): \"\"\"", "use_random_polarisation=False): super(SimpleSource, self).__init__() self.position = position self.direction = direction self.wavelength", "self.throw + 1 return photon class PlanarSource(object): \"\"\"A box that", "wavelength self.planeorigin = planeorigin self.planeextent = planeextent self.linepoint = np.array(linepoint)", "thetamin = 0, thetamax = np.pi): super(PointSource, self).__init__() self.spectrum =", "= phimin self.phimax = phimax self.thetamin = thetamin self.thetamax =", "<= 1.0: LOOP = False z = -1. + 2.", "1 intphi = np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi", "out of the plane in the GLOBAL FRAME. # i.e.", "np.random.uniform(0., self.length) y = np.random.uniform(0., self.width) local_point = (x, y,", "wavelength self.shape = Cylinder(radius = radius, length = length) self.radius", "a copy of the GNU General Public License # along", "+z to the direction of the photon vec = random_spherecial_vector()", "in solid angle specified by phimin, ..., thetamax \"\"\" def", "spectrum=None, wavelength=555, direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum", "photon.wavelength = self.wavelength # If use_polarisation is set generate a", "self.source_id = \"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon()", "self).__init__() self.position = position self.direction = direction self.wavelength = wavelength", "Laser(object): \"\"\"A light source that will generate photons of a", "= self.source_id photon.id = self.throw self.throw = self.throw + 1", "else: photon.wavelength = self.wavelength return photon class CylindricalSource(object): \"\"\" A", "r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y = r*np.sin(phi) z", "specified by phimin, ..., thetamax \"\"\" def __init__(self, spectrum =", "\"PointSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "the plane in the GLOBAL FRAME. # i.e. this is", "finite plane in it's local frame x = np.random.uniform(0., self.length)", "\"focussize\". The focus line should be perpendicular to the plane", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True return", "self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta) y =", "y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction = (x,y,z) photon.direction", "= \"SimpleSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source", "for photons emitted in a random direction and position inside", "None, wavelength = 555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin", "= direction/modulus # Wavelength if self.spectrum != None: photon.wavelength =", "= np.random.uniform(0., 2*np.pi) r = np.random.uniform(0.,self.radius) x = r*np.cos(phi) y", "!= None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active", "= self.linepoint[1] + np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] direction = focuspoint", "added (Angle of incidence in z-direction). \"\"\" def __init__(self, spectrum", "Trace import Photon from Geometry import Box, Cylinder, FinitePlane, transform_point,", "z-direction). \"\"\" def __init__(self, spectrum = None, wavelength = 555,", "theta(i) and phi(i) \"\"\" def __init__(self, spectrum = None, wavelength", "(at your option) any later version. # # pvtrace is", "0, planeorigin = (-1,-1,-1), planeextent = (-1,1,1)): super(LensSource, self).__init__() self.spectrum", "1, length = 10): super(CylindricalSource, self).__init__() self.spectrum = spectrum self.wavelength", "have received a copy of the GNU General Public License", "0, thetamax = np.pi, spacing=20): super(RadialSource, self).__init__() self.spectrum = spectrum", "= spacing self.throw = 0 self.source_id = \"RadialSource_\" + str(id(self))", "1 # Position of emission phi = np.random.uniform(0., 2*np.pi) r", "Laser is not set.\" self.polarisation = np.array(polarisation) self.throw = 0", "self.polarisation photon.id = self.throw self.throw = self.throw + 1 return", "phimin, ..., thetamax \"\"\" def __init__(self, spectrum = None, wavelength", "phi = intphi*(self.phimax-self.phimin)/self.spacing if self.thetamin == self.thetamax: theta = self.thetamin", "= True while LOOP: x = -1. + 2. *", "= direction self.wavelength = wavelength self.use_random_polarisation = use_random_polarisation self.throw =", "np.random.uniform(-self.focussize,self.focussize) focuspoint[2] = photon.position[2] + boost direction = focuspoint -", "of the finite plane in it's local frame x =", "tf from Trace import Photon from Geometry import Box, Cylinder,", "in the hope that it will be useful, # but", "LOOP: x = -1. + 2. * np.random.uniform() y =", "= tf.translation_matrix((0,0,0)) point = transform_point(self.center, transform) photon.direction = direction photon.position", "position inside a cylinder(radius, length) \"\"\" def __init__(self, spectrum =", "self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength photon.active = True return photon", "translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def photon(self):", "photon.active = True return photon class PointSource(object): \"\"\" A point", "photon(self): photon = Photon() photon.source = self.source_id photon.position = np.array(self.position)", "np from external.transformations import translation_matrix, rotation_matrix import external.transformations as tf", "the z-axis. \"\"\" def __init__(self, spectrum = None, wavelength =", "= self.source_id photon.position = np.array(self.position) photon.direction = np.array(self.direction) photon.active =", "= self.spectrum.wavelength_at_probability(np.random.uniform()) else: photon.wavelength = self.wavelength return photon class CylindricalSource(object):", "z = np.cos(theta) direction = (x,y,z) transform = tf.translation_matrix((0,0,0)) point", "np.random.uniform(self.planeorigin[1],self.planeextent[1]) z = np.random.uniform(self.planeorigin[2],self.planeextent[2]) photon.position = np.array((x,y,z)) # Direction focuspoint", "random_spherecial_vector() vec[2] = 0. vec = norm(vec) R = rotation_matrix_from_vector_alignment(self.direction,", "Free Software Foundation; either version 3 of the License, or", "= self.polarisation photon.id = self.throw self.throw = self.throw + 1", "photon.wavelength = self.wavelength return photon class LensSourceAngle(object): \"\"\" A source", "= np.random.uniform(self.planeorigin[2],self.planeextent[2]) - boost photon.position = np.array((x,y,z)) # Direction focuspoint", "Set wavelength of photon if self.spectrum != None: photon.wavelength =", "surface (normal), sampled from the spectrum.\"\"\" def __init__(self, spectrum=None, wavelength=555,", "photon.polarisation = transform_direction(vec, R) else: photon.polarisation = None photon.id =", "= True photon.wavelength = self.wavelength photon.polarisation = self.polarisation photon.id =", "self.throw = 0 self.source_id = \"LensSourceAngle_\" + str(id(self)) def photon(self):", "= point if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform()) else:", "= np.array(self.position) photon.direction = np.array(self.direction) photon.active = True photon.wavelength =", "polarisation vector of the photon if self.use_random_polarisation: # Randomise rotation", "incidence in z-direction). \"\"\" def __init__(self, spectrum = None, wavelength", "emits randomly in solid angle specified by phimin, ..., thetamax", "transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import Spectrum def random_spherecial_vector():", "xy-plane, the transform from +z to the direction of the", "def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position =", "with this program. If not, see <http://www.gnu.org/licenses/>. import numpy as", "Box, Cylinder, FinitePlane, transform_point, transform_direction, rotation_matrix_from_vector_alignment, norm from Materials import", "self.spacing = spacing self.throw = 0 self.source_id = \"RadialSource_\" +", "photon.polarisation = self.polarisation photon.id = self.throw self.throw = self.throw +", "np.random.randint(1, self.spacing+1) inttheta = np.random.randint(1, self.spacing+1) phi = intphi*(self.phimax-self.phimin)/self.spacing if", "= a * x y = a * y return", "Public License as published by # the Free Software Foundation;", "2. * np.random.uniform() y = -1. + 2. * np.random.uniform()", "is not set.\" self.polarisation = np.array(polarisation) self.throw = 0 self.source_id", "this lense an additional z-boost is added (Angle of incidence", "of the photon if self.use_random_polarisation: # Randomise rotation angle around", "theta = self.thetamin else: theta = inttheta*(self.thetamax-self.thetamin)/self.spacing x = np.cos(phi)*np.sin(theta)", "direction=(0,0,1), length=0.05, width=0.05): super(PlanarSource, self).__init__() self.spectrum = spectrum self.wavelength =", "self.center = center self.phimin = phimin self.phimax = phimax self.thetamin", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "generated in a plane are focused on a line with", "wavelength of photon if self.spectrum != None: photon.wavelength = self.spectrum.wavelength_at_probability(np.random.uniform())", "the direction that photons are fired out of the plane", "position.\"\"\" def __init__(self, position=[0,0,0], direction=[0,0,1], wavelength=555, use_random_polarisation=False): super(SimpleSource, self).__init__() self.position", "photon.wavelength = self.wavelength return photon class LensSource(object): \"\"\" A source", "# Direction focuspoint = np.array((0.,0.,0.)) focuspoint[0] = self.linepoint[0] + np.random.uniform(-self.focussize,self.focussize)", "r*np.cos(phi) y = r*np.sin(phi) z = np.random.uniform(0.,self.length) local_center = (x,y,z)", "self.focussize = focussize self.angle = angle self.throw = 0 self.source_id", "translate(self, translation): self.shape.append_transform(tf.translation_matrix(translation)) def rotate(self, angle, axis): self.shape.append_transform(tf.rotation_matrix(angle, axis)) def", "self.thetamin = thetamin self.thetamax = thetamax self.throw = 0 self.source_id", "photon.active = True return photon class RadialSource(object): \"\"\" A point", "(-1,1,1)): super(LensSource, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin", "= length self.throw = 0 self.source_id = \"CylindricalSource_\" + str(id(self))", "GNU General Public License for more details. # # You", "= (direction[0]**2+direction[1]**2+direction[2]**2)**0.5 photon.direction = direction/modulus # Wavelength if self.spectrum !=", "of the photon vec = random_spherecial_vector() vec[2] = 0. vec", "0, phimax = 2*np.pi, thetamin = 0, thetamax = np.pi,", "super(LensSourceAngle, self).__init__() self.spectrum = spectrum self.wavelength = wavelength self.planeorigin =", "# Transform the direciton photon.position = transform_point(local_point, self.plane.transform) photon.direction =", "from +z to the direction of the photon vec =", "\"\"\" def __init__(self, spectrum = None, wavelength = 555, radius", "= np.random.uniform(0.,np.pi) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z =", "\"RadialSource_\" + str(id(self)) def photon(self): photon = Photon() photon.source =", "555, linepoint=(0,0,0), linedirection=(0,0,1), focussize = 0, planeorigin = (-1,-1,-1), planeextent", "is distributed in the hope that it will be useful,", "self.width) local_point = (x, y, 0.) # Transform the direciton", "3 of the License, or # (at your option) any", "and aligned with the z-axis. \"\"\" def __init__(self, spectrum =", "rotate(self, angle, axis): self.plane.append_transform(tf.rotation_matrix(angle, axis)) def photon(self): photon = Photon()", "= 555, radius = 1, length = 10): super(CylindricalSource, self).__init__()", "import Photon from Geometry import Box, Cylinder, FinitePlane, transform_point, transform_direction,", "spectrum self.wavelength = wavelength self.center = center self.phimin = phimin", "= wavelength self.center = center self.phimin = phimin self.phimax =", "# Randomise rotation angle around xy-plane, the transform from +z", "np.array(position) self.direction = np.array(direction) self.wavelength = wavelength assert polarisation !=", "= 0 self.source_id = \"LaserSource_\" + str(id(self)) def photon(self): photon", "+ 1 phi = np.random.uniform(self.phimin, self.phimax) theta = np.random.uniform(self.thetamin, self.thetamax)", "# # You should have received a copy of the", "self.thetamax = thetamax self.throw = 0 self.source_id = \"PointSource_\" +", "= np.random.uniform(self.thetamin, self.thetamax) x = np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z", "the finite plane in it's local frame x = np.random.uniform(0.,", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "= np.cos(phi)*np.sin(theta) y = np.sin(phi)*np.sin(theta) z = np.cos(theta) local_direction =", "self.throw self.throw = self.throw + 1 return photon class Laser(object):", "\"\"\" A point source that emits at discrete angles theta(i)", "without even the implied warranty of # MERCHANTABILITY or FITNESS", "- s) x = a * x y = a" ]
[ "and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and", ">>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self,", "[b.value for b in bs] [0, 0, 0, 1, 1,", "bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self,", "\"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>>", "all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self,", "= output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "... results.append(ns == c.evaluate([x, x, x, y, y, y])) >>>", "inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ... ns =", "[0], [1]] >>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2):", "[1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>> [b.value for", "= bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>>", "if isinstance(other, list) and len(other) > 0 and isinstance(other[0], int):", "args]) # Return output from hook if it exists and", "return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>> results", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ...", "def __lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>>", "bits([constant(0)]*n) def __new__(cls, argument = None) -> bits: \"\"\" Return", "in self]) def and_(self: bits, other: bits) -> bits: \"\"\"", "output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "in zip(self, other)]) def __xor__(self: bits, other: bits) -> bits:", ">>> all(results) True \"\"\" return bits([x.or_(y) for (x, y) in", "set) and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return", "representing an abstract bit. Such a bit can be interpreted", "b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "\"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>>", "return self.nif(other) def xor(self, other): \"\"\" >>> results = []", "bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs", "can only subtract a bit from the integer 1 \"\"\"", "return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit())", "hook @staticmethod def operation(o, *args): # Ensure second argument is", "in zip(self, other)]) def if_(self: bits, other: bits) -> bits:", "\"\"\" Class for representing an abstract bit. Such a bit", "# Ensure second argument is a `bit`. args = list(args)", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def", "in zip(self, other)]) def nand_(self: bits, other) -> bits: \"\"\"", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ...", "... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls,", "output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "try: # Construct the circuit and add it to the", ">>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self,", "\"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>>", "\"\"\" return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>>", "... def equal(x, y): ... return x & y Traceback", "x in [0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_())", "for bs in bss] [[1], [1, 1, 1], [0, 0,", "for x in (0, 1) for y in (0, 1)]", "[conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0, 0], [1,", "__rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0 &", "[] >>> for x in [0, 1]: ... bit.circuit(circuit()) ...", "= output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\"", "PEP 563. eval_ = lambda a: eval(a) if isinstance(a, str)", "disable=W0123 try: # Construct the circuit and add it to", "zip(self, other)]) def nand_(self: bits, other) -> bits: \"\"\" >>>", "]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit())", "= outputs(xs.nor_(ys)) ... ns = [int(z) for z in zs]", "Such a bit can be interpreted concretely as a value,", "& ys) ... ns = [int(z) for z in zs]", "def nor(self: bits, other: bits) -> bits: \"\"\" >>> results", "operation on the arguments. v = o(*[a.value for a in", "return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def __eq__(self:", "[0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>> [b.value for", "reversed(self))) def not_(self: bits) -> bits: \"\"\" >>> results =", "circuits. Embedded domain-specific combinator library for assembling abstract definitions of", "def nif(self: bits, other: bits) -> bits: \"\"\" >>> results", "y])) ... zs = outputs(xs.and_(ys)) ... ns = [int(z) for", "circuits and synthesizing circuits from those definitions. \"\"\" from __future__", "inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ... ns =", "True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\"", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def", "... ys = outputs(xs.not_()) ... ns = [int(y) for y", "... bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ... results.append(int(b)", "return self.value def not_(self): \"\"\" >>> results = [] >>>", "b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "__and__(self, other): \"\"\" >>> results = [] >>> for (x,", "bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>> results =", "those operators. >>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit())", "return map(bits, parts(self, other)) # Number of parts is `other`.", "if it exists and if # it returns an output.", "b = output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bits([x.nand_(y) for (x, y) in zip(self, other)]) def __rshift__(self: bits,", "b = output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>>", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) ==", "that is designated as a constant input.\"\"\" class input(bit): \"\"\"Bit", "= [int(y) for y in ys] ... c = bit.circuit()", "0, 0, 0, 0, 1] \"\"\" if isinstance(other, set) and", "\"\"\"Bit that is designated as a variable input from one", "isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two):", "... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "return bits([x.imp_(y) for (x, y) in zip(self, other)]) def imp_(self:", "bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "self]) def and_(self: bits, other: bits) -> bits: \"\"\" >>>", ">>> b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0, 1,", "> ys) ... ns = [int(z) for z in zs]", "_hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_ is not", "... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "xnor(self, other): \"\"\" >>> results = [] >>> for (x,", "from the integer 1') def and_(self, other): \"\"\" >>> results", "all(results) True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other):", "x, x]), inputs([y, y, y])) ... zs = outputs(xs >=", "signature class bit(): \"\"\" Class for representing an abstract bit.", "^ constant(0) >>> b.value 1 \"\"\" return self ^ (constant(other)", "zip(self, other)]) def __mod__(self, other) -> bits: \"\"\" >>> results", "bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated as a", "y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for (x,", "for (x, y) in zip(self, other)]) def nor_(self: bits, other:", "def nand_(self, other): \"\"\" >>> results = [] >>> for", "else: return map(bits, parts(self, other)) # Number of parts is", "return map(bits, parts(self, length=other)) # Sequence of lengths. elif isinstance(other,", "ready as final output or whether there are others dependent", "bit.circuit(circuit()) ... b = output(input(x) & input(y)) ... results.append(int(b) ==", "def __ge__(self, other): \"\"\" >>> results = [] >>> for", "bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self", "... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "int) else other) def or_(self, other): \"\"\" >>> results =", "other) def nor(self, other): \"\"\" >>> results = [] >>>", "y, y])) ... zs = outputs(xs >= ys) ... ns", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def", "x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ... ns", "def if_(self: bits, other: bits) -> bits: \"\"\" >>> results", "def __le__(self, other): \"\"\" >>> results = [] >>> for", "bits object given the supplied argument. \"\"\" return bits_type(argument)\\ if", "for y in ys] ... c = bit.circuit() ... results.append(ns", "y])) ... zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for", "other) def __eq__(self, other): \"\"\" >>> results = [] >>>", "return bits([x.nif_(y) for (x, y) in zip(self, other)]) def xor(self:", "to represent the wires within a circuit built up out", "input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return", "raise RuntimeError('automated circuit synthesis failed') from None # Return the", "\"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1,", ">>> b = 1 ^ constant(0) >>> b.value 1 \"\"\"", "output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "imp_(self, other): \"\"\" >>> results = [] >>> for (x,", "\"\"\" >>> bit.circuit(circuit()) >>> b = 0 & constant(1) >>>", "0, 0, 0, 1, 0, 1, 1, 0, 0, 0,", "def imp(self, other): \"\"\" >>> results = [] >>> for", "types/signature from # the type annotation of the decorated function.", "bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>> results =", "whether there are others dependent on it. if len(b.gate.outputs) >", "v, *args) if r is not None: return r return", "if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity =", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b)", "a) in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit", "Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: #", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.or_(y)", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y)", "isinstance(other, list) and len(other) > 0 and isinstance(other[0], int): return", "the value of the result of the operation on the", "-> bits: \"\"\" Overloaded operator: rotation and shift operations. >>>", "else other) def or_(self, other): \"\"\" >>> results = []", "bs << 3 >>> [b.value for b in bs] [1,", "if gate_ is None else gate_ def __int__(self): return self.value", "... bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ... results.append(int(b)", "bit._circuit.gate() if gate_ is None else gate_ def __int__(self): return", "bit is ready as final output or whether there are", "input from a second source.\"\"\" class output(bit): \"\"\" Bit that", "__rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator: rotation and", "bs in bss] [[1], [1, 1, 1], [0, 0, 0,", "the result of the operation on the arguments. v =", "variable input from a second source.\"\"\" class output(bit): \"\"\" Bit", "y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys]", "o(*[a.value for a in args]) # Return output from hook", "outputs(xs.not_()) ... ns = [int(y) for y in ys] ...", "0 & constant(1) >>> b.value 0 \"\"\" return self &", "== c.evaluate([x, x, x, y, y, y])) >>> all(results) True", "b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "bits([x.imp_(y) for (x, y) in zip(self, other)]) def imp_(self: bits,", "outputs(xs.and_(ys)) ... ns = [int(z) for z in zs] ...", "all(results) True \"\"\" return bit.operation(op.if_, self, other) def imp(self, other):", "= [int(z) for z in zs] ... c = bit.circuit()", "__invert__(self): \"\"\" >>> results = [] >>> for x in", "__xor__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for (x,", "... zs = outputs(xs.nor_(ys)) ... ns = [int(z) for z", "True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\"", "bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0, 1, 1,", "def xor_(self: bits, other: bits) -> bits: \"\"\" >>> results", "x]), inputs([y, y, y])) ... zs = outputs(xs ^ ys)", ">>> bs = bs >> {3} >>> [b.value for b", "type_out = lambda a: output if a is bit else", "bits: \"\"\" >>> results = [] >>> for x in", "self) raise ValueError('can only subtract a bit from the integer", "# Preserve the bit by copying it to a new", "-> int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0,", "def nand(self, other): \"\"\" >>> results = [] >>> for", "output type of a function decorated for automated synthesis. \"\"\"", "is designated as a variable input.\"\"\" def __init__(self: bit, value:", ">>> all(results) True \"\"\" return self.nif(other) def xor(self, other): \"\"\"", "... zs = outputs(xs | ys) ... ns = [int(z)", "= outputs(xs.xor_(ys)) ... ns = [int(z) for z in zs]", "byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod", "Preserve the bit by copying it to a new wire.", "inputs([y, y, y])) ... zs = outputs(xs | ys) ...", "== ys) ... ns = [int(z) for z in zs]", "0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss", "= output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "for b in bs] [1, 0, 0, 0, 0, 0,", "\"\"\" Class for representing an input or output type of", "for (x, y) in zip(self, other)]) def __xor__(self: bits, other:", "other) def nor_(self, other): \"\"\" >>> results = [] >>>", "(constant(other) if isinstance(other, int) else other) def nimp(self, other): \"\"\"", "[1, 0], [1, 1]] >>> @synthesize ... def equal(x, y):", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) &", "xor(self, other): \"\"\" >>> results = [] >>> for (x,", "bit. Such a bit can be interpreted concretely as a", "argument) def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>>", "bits([x.nif_(y) for (x, y) in zip(self, other)]) def __lt__(self: bits,", "- x) & (1 - y)) >>> xys = [bits([x,", "bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>> results =", "in (0, 1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy)", "[0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x])", "bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>> results =", "# Construct the circuit and add it to the function", "other)]) def nand(self: bits, other) -> bits: \"\"\" >>> results", "bs] [1, 1, 1, 0, 0, 0, 0, 1] \"\"\"", "None # Return the original function. return f if __name__", "also used to keep track of relationships between operators and", "x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ... ns", "> 0: b = ~(~b) # Preserve the bit by", "def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value", "True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)])", "other)]) def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator:", "bits([x.if_(y) for (x, y) in zip(self, other)]) def imp(self: bits,", "self, other) def __xor__(self, other): \"\"\" >>> results = []", "y) in zip(self, other)]) def __mod__(self, other) -> bits: \"\"\"", "in zip(self, other)]) def or_(self: bits, other: bits) -> bits:", "None: return type(b1) else: return bit \"\"\" return bit @staticmethod", "= 1 ^ constant(0) >>> b.value 1 \"\"\" return self", "variable input from one source.\"\"\" class input_two(input): \"\"\"Bit that is", "def __init__(self, value, gate_=None): self.value = value self.gate = bit._circuit.gate()", "output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "definitions of logic circuits and synthesizing circuits from those definitions.", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self,", "there are others dependent on it. if len(b.gate.outputs) > 0:", "[0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b)", "y, y])) ... zs = outputs(xs.nimp(ys)) ... ns = [int(z)", "input(bit): \"\"\"Bit that is designated as a variable input.\"\"\" def", "output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "return bits([x.xor_(y) for (x, y) in zip(self, other)]) def __xor__(self:", "copying it to a new wire. self.value = b.value self.gate", "for x in [0, 1]: ... bit.circuit(circuit()) ... b =", "an input or output type of a function decorated for", "x]), inputs([y, y, y])) ... zs = outputs(xs >= ys)", "bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing an input", "return bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of", "def nor_(self, other): \"\"\" >>> results = [] >>> for", "bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod def constructor(b1,", "sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits)", "isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits) -> int:", "bit: ... return (x & y) | ((1 - x)", "output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "def __lt__(self, other): \"\"\" >>> results = [] >>> for", "else other) def nimp(self, other): \"\"\" >>> results = []", "... bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ... results.append(int(b)", "y])) ... zs = outputs(xs.or_(ys)) ... ns = [int(z) for", "in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def from_bytes(bytes_,", "other)]) def __ge__(self: bits, other: bits) -> bits: \"\"\" >>>", "for a in args]) # Return output from hook if", "= outputs(xs % ys) ... ns = [int(z) for z", "return bits([x.if_(y) for (x, y) in zip(self, other)]) def __ge__(self:", "= output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "other def constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input,", "None _hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_ is", "circuit and add it to the function as an attribute.", "return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self:", "other)]) def nimp_(self: bits, other: bits) -> bits: \"\"\" >>>", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other)", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_,", "typing import Sequence import doctest from parts import parts from", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys))", "`bit` or `bits`. >>> @synthesize ... def equal(x: bit, y:", "return bits([x.and_(y) for (x, y) in zip(self, other)]) def __and__(self:", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys))", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_,", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3", "bss[1]]) ([1, 1, 1, 1], [0, 0, 0, 0]) >>>", ">>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self,", "b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", ">>> b.value 1 \"\"\" return self | (constant(other) if isinstance(other,", "nor(self, other): \"\"\" >>> results = [] >>> for (x,", "def if_(self, other): \"\"\" >>> results = [] >>> for", "args = list(args) if len(args) == 2: args[1] = constant(args[1])", "2: args[1] = constant(args[1]) if isinstance(args[1], int) else args[1] #", "... ys = outputs(~xs) ... ns = [int(y) for y", "in zip(self, other)]) def __or__(self: bits, other: bits) -> bits:", "call last): ... RuntimeError: automated circuit synthesis failed \"\"\" #", "attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k, a)", "... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "input_two(input): \"\"\"Bit that is designated as a variable input from", "int): return map(bits, parts(self, length=other)) # Sequence of lengths. elif", "return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit())", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs =", "bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation = None @staticmethod", "in zip(self, other)]) def imp(self: bits, other: bits) -> bits:", "def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>>", "ns = [int(z) for z in zs] ... c =", "make_hook(bit_): ... def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o,", "bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>> results =", "constant(args[1]) if isinstance(args[1], int) else args[1] # Compute the value", "= outputs(xs < ys) ... ns = [int(z) for z", "bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from None #", "return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits:", ">>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def imp(self,", "x) & (1 - y)) >>> xys = [bits([x, y])", "result = list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other)", "y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for (x, y)", "True \"\"\" return self.nif(other) def xor(self, other): \"\"\" >>> results", "1, 1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>>", "xys] [[0, 0], [0, 0], [1, 0], [1, 1]] >>>", "in bs] [1, 0, 0, 0, 0, 0, 0, 0]", "0, 0, 1, 0, 1, 1, 0, 0, 0, 0,", "return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>> results", "None else gate_ def __int__(self): return self.value def not_(self): \"\"\"", "constant input.\"\"\" class input(bit): \"\"\"Bit that is designated as a", "0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs", "def nor(self, other): \"\"\" >>> results = [] >>> for", "= value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that", "and_(self, other): \"\"\" >>> results = [] >>> for (x,", "isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0]", "def __matmul__(self, other): \"\"\" >>> results = [] >>> for", "range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>>", "\"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>>", "[b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self: bit,", "True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)])", ">>> all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y)))", "[1, 1, 1, 0, 0, 0, 0, 1] \"\"\" if", "\"\"\"Embedded DSL for assembling logic circuits. Embedded domain-specific combinator library", ">>> all(results) True \"\"\" return bits([x.if_(y) for (x, y) in", "= output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "= outputs(xs.nimp(ys)) ... ns = [int(z) for z in zs]", "for b in bss[1]]) ([1, 1, 1, 1], [0, 0,", "bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self):", "`bit`. args = list(args) if len(args) == 2: args[1] =", "constructor(b1, b2=None): # The inference code below is not currently", "of logic circuits and synthesizing circuits from those definitions. \"\"\"", "if a is bit else inputs([0] * a) type_out =", "*args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args]))", "== bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation = None", "in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\"", "b = 0 & constant(1) >>> b.value 0 \"\"\" return", "y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for (x, y)", "all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other):", "= bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>> all(results)", "return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>> results", "all(results) True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other):", "y])) ... zs = outputs(xs.nand_(ys)) ... ns = [int(z) for", "args_in = { k: type_in(eval_(a)) for (k, a) in f.__annotations__.items()", "all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other):", "y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for (x, y)", "zip(self, other)]) def nor(self: bits, other: bits) -> bits: \"\"\"", "all(results) True \"\"\" return self.nif(other) def xor(self, other): \"\"\" >>>", ">>> b = 1 | constant(0) >>> b.value 1 \"\"\"", "a function decorated for automated synthesis. \"\"\" class bits(list): \"\"\"", "bss] [[1], [1, 1, 1], [0, 0, 0, 0]] \"\"\"", "else other) def nor(self, other): \"\"\" >>> results = []", "import op, gate, circuit, signature class bit(): \"\"\" Class for", "== bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self) def", "= output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "y) in zip(self, other)]) def __and__(self: bits, other: bits) ->", ">>> all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\"", "xys = [bits([x, y]) for x in (0, 1) for", "... def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0]", "input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and", "1], [0, 0, 0, 0]] \"\"\" if isinstance(other, list) and", "\"\"\" return bits([x.not_() for x in self]) def __invert__(self: bits)", "\"\"\" return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def", "\"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)]) def", "from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_) for bit_", "int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0])", "other)]) def or_(self: bits, other: bits) -> bits: \"\"\" >>>", "True \"\"\" return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\"", "bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit())", "b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self: bit, b:", "[a.gate for a in args])) @staticmethod def constructor(b1, b2=None): #", "class output(bit): \"\"\" Bit that is designated an output. >>>", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) ==", "inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ... ns =", "zip(self, other)]) def nimp(self: bits, other: bits) -> bits: \"\"\"", "set) and len(other) == 1 and isinstance(list(other)[0], int): return self", "= [bits([x, y]) for x in (0, 1) for y", "bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "for (x, y) in zip(self, other)]) def __and__(self: bits, other:", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ...", "\"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>>", "output(bit): \"\"\" Bit that is designated an output. >>> bit.circuit(circuit())", "nif(self, other): \"\"\" >>> results = [] >>> for (x,", "__eq__(self, other): \"\"\" >>> results = [] >>> for (x,", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ...", "-> bit: ... return (x & y) | ((1 -", "return bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit())", "list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other) -> bits:", "bit.circuit(circuit()) ... b = output(input(x) == input(y)) ... results.append(int(b) ==", "if isinstance(a, str) else a # pylint: disable=W0123 try: #", "is not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for", "True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent", "and if # it returns an output. if bit._hook_operation is", "automatically synthesizing a circuit from a function that takes only", "b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True", "determining types/signature from # the type annotation of the decorated", "wires within a circuit built up out of those operators.", "for (x, y) in zip(self, other)]) def nor(self: bits, other:", "self, other) def __gt__(self, other): \"\"\" >>> results = []", "< ys) ... ns = [int(z) for z in zs]", "+ other def constants(l): return bits(map(constant, l)) def inputs(l): return", "a bit from the integer 1') def and_(self, other): \"\"\"", "list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit())", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def", "y])) ... zs = outputs(xs.imp_(ys)) ... ns = [int(z) for", "[[b.value for b in bs] for bs in bss] [[1],", "y) in zip(self, other)]) def __or__(self: bits, other: bits) ->", "other)]) def nor(self: bits, other: bits) -> bits: \"\"\" >>>", "be interpreted concretely as a value, but it is also", "__le__(self, other): \"\"\" >>> results = [] >>> for (x,", "1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "bs = bs >> {3} >>> [b.value for b in", "represent the wires within a circuit built up out of", "zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for z in", "and/or `bits` objects as its arguments and returns an output", ">>> all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in", "is None else gate_ def __int__(self): return self.value def not_(self):", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def", "... b = output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0])", "\"\"\" >>> bit.circuit(circuit()) >>> b = 1 | constant(0) >>>", "[[1, 1], [1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit())", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) ==", "self, other) def __matmul__(self, other): \"\"\" >>> results = []", "constructor) ]) @staticmethod def zeros(n: int) -> bits: \"\"\" >>>", "y, y])) ... zs = outputs(xs.nif(ys)) ... ns = [int(z)", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys))", "bs] for bs in bss] [[1], [1, 1, 1], [0,", "input from one source.\"\"\" class input_two(input): \"\"\"Bit that is designated", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def nif(self,", "__init__(self: bit, b: bit): # Check if bit is ready", "in zip(self, other)]) def xnor_(self: bits, other: bits) -> bits:", "def __ge__(self: bits, other: bits) -> bits: \"\"\" >>> results", "def constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input, l))", "conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0] & xy[1])", "is_input=True) class input_one(input): \"\"\"Bit that is designated as a variable", "bits([x.or_(y) for (x, y) in zip(self, other)]) def __or__(self: bits,", "self, other) def __or__(self, other): \"\"\" >>> results = []", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) ==", ">> {3} >>> [b.value for b in bs] [1, 1,", ">>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __rxor__(self,", "all(results) True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other):", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other)", "bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing a", "op, gate, circuit, signature class bit(): \"\"\" Class for representing", "bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y)))", "function that takes only `bit` and/or `bits` objects as its", "== c.evaluate([x, x, x])) >>> all(results) True \"\"\" return bits([x.not_()", "(x, y) in zip(self, other)]) def nimp(self: bits, other: bits)", "\"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation. quantity", "y, y])) ... zs = outputs(xs.imp(ys)) ... ns = [int(z)", "imp_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "... ValueError: can only subtract a bit from the integer", "return bits([x.xor_(y) for (x, y) in zip(self, other)]) def or_(self:", "= outputs(xs ^ ys) ... ns = [int(z) for z", "0, 0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "\"\"\" >>> results = [] >>> for x in [0,", "input_one(input): \"\"\"Bit that is designated as a variable input from", "self) def __rsub__(self, other): \"\"\" >>> results = [] >>>", "gate, circuit, signature class bit(): \"\"\" Class for representing an", "concretely as a value, but it is also used to", "from typing import Sequence import doctest from parts import parts", "xor(self: bits, other: bits) -> bits: \"\"\" >>> results =", "other)]) def __gt__(self: bits, other: bits) -> bits: \"\"\" >>>", "bit_.gate(o, [a.gate for a in args])) ... return hook >>>", "if r is not None: return r return bit.constructor(*args)(v, bit.gate(o,", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ...", "y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for (x, y)", "xnor(self: bits, other: bits) -> bits: \"\"\" >>> results =", "b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0,", "outputs(xs.nimp_(ys)) ... ns = [int(z) for z in zs] ...", "bits([x.xnor_(y) for (x, y) in zip(self, other)]) def __eq__(self: bits,", "igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value =", "return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def", "bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o, v, *args):", "all(results) True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other):", "in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\" >>>", "self, other) def __lt__(self, other): \"\"\" >>> results = []", "in [0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x, x,", "return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>> results", "^ (constant(other) if isinstance(other, int) else other) def or_(self, other):", "inputs([y, y, y])) ... zs = outputs(xs ^ ys) ...", "\"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>> results =", "... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "Embedded domain-specific combinator library for assembling abstract definitions of logic", "zs = outputs(xs & ys) ... ns = [int(z) for", "for (x, y) in zip(self, other)]) def imp_(self: bits, other:", "for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int)", ">>> all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in", "ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument", "designated as a variable input.\"\"\" def __init__(self: bit, value: int):", ">>> bit.circuit(circuit()) >>> b = 1 | constant(0) >>> b.value", "zip(self, other)]) def imp(self: bits, other: bits) -> bits: \"\"\"", "/ {2}) >>> [[b.value for b in bs] for bs", "inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns =", "\"\"\"Bit that is designated as a constant input.\"\"\" class input(bit):", ">>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i)", "ys) ... ns = [int(z) for z in zs] ...", "for a in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>>", "y])) ... zs = outputs(xs.nimp(ys)) ... ns = [int(z) for", "= output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "input(0) if a is bit else inputs([0] * a) type_out", "bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^ constant(0)", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ...", "\"\"\" return bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>>", "... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys", "\"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return bits([", "bits: \"\"\"Concatenation of bit vectors.\"\"\" return self + other def", "class bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing an", "(len(self)//list(other)[0]) # Parts of length `other`. else: return map(bits, parts(self,", "0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _ in range(other)])", "bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True", "in zip(self, other)]) def __le__(self: bits, other: bits) -> bits:", "0]] \"\"\" if isinstance(other, list) and len(other) > 0 and", "of type `bit` or `bits`. >>> @synthesize ... def equal(x:", "bit.operation(op.imp_, self, other) def nand(self, other): \"\"\" >>> results =", "bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ... results.append(int(b) ==", "else\\ list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\" >>>", "circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None):", "for (x, y) in zip(self, other)]) def imp(self: bits, other:", "x, x]), inputs([y, y, y])) ... zs = outputs(xs <=", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y)", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self,", "constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ])", "0], [1, 0], [1, 1]] >>> @synthesize ... def equal(x,", "and b2 is None: return type(b1) else: return bit \"\"\"", "other) def __mod__(self, other): \"\"\" >>> results = [] >>>", "int, constructor=bit) -> bits: return bits([ constructor(bit_) for bit_ in", "y) in zip(self, other)]) def xor(self: bits, other: bits) ->", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y)", "is designated as a constant input.\"\"\" class input(bit): \"\"\"Bit that", "return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results =", "0, 0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int):", "3 >>> [b.value for b in bs] [1, 0, 0,", "y])) ... zs = outputs(xs.nif_(ys)) ... ns = [int(z) for", "return (xy[0], xy[0] & xy[1]) >>> xys = [bits([x, y])", "k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise", "= { k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if", "outputs(xs.xor_(ys)) ... ns = [int(z) for z in zs] ...", "if isinstance(other, int) else other) def or_(self, other): \"\"\" >>>", "for (x, y) in zip(self, other)]) def nand(self: bits, other)", "[[0, 0], [0, 0], [1, 0], [1, 1]] >>> @synthesize", "1, 1, 0, 0, 0, 0, 0, 0, 0, 0]", "not None: r = bit._hook_operation(o, v, *args) if r is", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other)", "1, 1], [0, 0, 0, 0]] \"\"\" if isinstance(other, list)", "else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits,", "`other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation of bit", "> input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "\"\"\" return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>>", "bits(2): ... return (xy[0], xy[0] & xy[1]) >>> xys =", "bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "y, y])) ... zs = outputs(xs.nor(ys)) ... ns = [int(z)", "= bs >> {3} >>> [b.value for b in bs]", "other)]) def xnor_(self: bits, other: bits) -> bits: \"\"\" >>>", "bits([x.xnor_(y) for (x, y) in zip(self, other)]) def if_(self: bits,", "return (x & y) | ((1 - x) & (1", "raise ValueError('can only subtract a bit from the integer 1')", "True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\"", "isinstance(other, int) else other) def nor(self, other): \"\"\" >>> results", "outputs(xs % ys) ... ns = [int(z) for z in", "in zip(self, other)]) def nif_(self: bits, other: bits) -> bits:", "... zs = outputs(xs.imp_(ys)) ... ns = [int(z) for z", "y, y])) ... zs = outputs(xs.nand(ys)) ... ns = [int(z)", "RuntimeError('automated circuit synthesis failed') from None # Return the original", "v, *args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>>", "hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a", "nand(self: bits, other) -> bits: \"\"\" >>> results = []", "= output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity])", "if other == 1: return bit.operation(op.not_, self) raise ValueError('can only", "[b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class for", "b = output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "return bits([x.nand_(y) for (x, y) in zip(self, other)]) def nand_(self:", "b in bss[0]], [b.value for b in bss[1]]) ([1, 1,", "bit.circuit(circuit()) >>> b = 1 | constant(0) >>> b.value 1", "return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod def", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) ==", "one source.\"\"\" class input_two(input): \"\"\"Bit that is designated as a", "for (x, y) in zip(self, other)]) def __eq__(self: bits, other:", "1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None) ->", "b in bs] [1, 0, 0, 0, 0, 0, 0,", "the decorated function. type_in = lambda a: input(0) if a", "[0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "in zip(self, other)]) def nimp_(self: bits, other: bits) -> bits:", "return bit.operation(op.not_, self) raise ValueError('can only subtract a bit from", "bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n:", "True \"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>> results", "[0, 1]: ... bit.circuit(circuit()) ... b = output(1 - input(x))", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys))", "bs >> {3} >>> [b.value for b in bs] [1,", "return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value = value", "import Sequence import doctest from parts import parts from circuit", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs,", "inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ... ns =", "outputs(xs.nand_(ys)) ... ns = [int(z) for z in zs] ...", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) > input(y)) ...", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys))", "from one source.\"\"\" class input_two(input): \"\"\"Bit that is designated as", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) |", "is not currently in use. \"\"\" if isinstance(b1, input_one) and", "bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o,", "bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value = value self.gate", "y) in zip(self, other)]) def __gt__(self: bits, other: bits) ->", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) | input(y))", "\"\"\" return self & (constant(other) if isinstance(other, int) else other)", "results = [] >>> for x in [0, 1]: ...", "bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return", "0, 0]] \"\"\" if isinstance(other, list) and len(other) > 0", "bits([x.xor_(y) for (x, y) in zip(self, other)]) def or_(self: bits,", "x in [0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x))", "= lambda a: eval(a) if isinstance(a, str) else a #", "[b.value for b in bss[1]]) ([1, 1, 1, 1], [0,", "def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded operator: rotation", "a variable input from a second source.\"\"\" class output(bit): \"\"\"", "all(results) True \"\"\" return bits([x.and_(y) for (x, y) in zip(self,", "x]), inputs([y, y, y])) ... zs = outputs(xs.imp_(ys)) ... ns", "integer 1') def and_(self, other): \"\"\" >>> results = []", "\"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>>", "y, y])) ... zs = outputs(xs <= ys) ... ns", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys))", "def nif_(self: bits, other: bits) -> bits: \"\"\" >>> results", "representing a vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_:", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) ==", "def __eq__(self, other): \"\"\" >>> results = [] >>> for", "outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b)", "as a variable input.\"\"\" def __init__(self: bit, value: int): self.value", "in zip(self, other)]) def __gt__(self: bits, other: bits) -> bits:", "results.append(ns == c.evaluate([x, x, x, y, y, y])) >>> all(results)", "other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "__mod__(self, other): \"\"\" >>> results = [] >>> for (x,", "and isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence of", ">>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self,", "zs = outputs(xs.nif_(ys)) ... ns = [int(z) for z in", "results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2", ">>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self,", "bits, other) -> bits: \"\"\" Overloaded operator: rotation and shift", "return bit.operation(op.if_, self, other) def imp(self, other): \"\"\" >>> results", "output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "__or__(self, other): \"\"\" >>> results = [] >>> for (x,", "[0, 0], [1, 0], [1, 1]] >>> @synthesize ... def", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b)", "b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0]", "for i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) ->", "x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ... ns", "args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b", "def xor(self: bits, other: bits) -> bits: \"\"\" >>> results", "if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except:", "\"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result)", "output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value, b2.value] [0,", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys))", "all(results) True \"\"\" return bits([x.or_(y) for (x, y) in zip(self,", "(1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x,", "for xy in xys] [[1], [0], [0], [1]] >>> @synthesize", "zip(self, other)]) def __and__(self: bits, other: bits) -> bits: \"\"\"", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>>", "def and_(self, other): \"\"\" >>> results = [] >>> for", "failed \"\"\" # Functions for determining types/signature from # the", "on the arguments. v = o(*[a.value for a in args])", "self.nif(other) def xor(self, other): \"\"\" >>> results = [] >>>", "bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self:", ">>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_())", "(x, y) in zip(self, other)]) def __mod__(self, other) -> bits:", "of the operation on the arguments. v = o(*[a.value for", "ys = outputs(xs.not_()) >>> [y.value for y in ys] [1,", "ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for", "Bit that is designated an output. >>> bit.circuit(circuit()) >>> b0", "True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)])", "for representing an abstract bit. Such a bit can be", "operators. >>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>>", ">>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def", "def xnor_(self, other): \"\"\" >>> results = [] >>> for", "for x in self]) def and_(self: bits, other: bits) ->", "inputs([y, y, y])) ... zs = outputs(xs > ys) ...", "list(bs / 2) >>> ([b.value for b in bss[0]], [b.value", "currently in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one):", "r = bit._hook_operation(o, v, *args) if r is not None:", "bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def __pow__(self:", "= output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "4]) >>> [[b.value for b in bs] for bs in", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys))", "is ready as final output or whether there are others", "the type annotation of the decorated function. type_in = lambda", "-> bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for", "if_(self, other): \"\"\" >>> results = [] >>> for (x,", "zs = outputs(xs.nor_(ys)) ... ns = [int(z) for z in", "True \"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)])", "in zip(self, other)]) def nand(self: bits, other) -> bits: \"\"\"", "b in bss[1]]) ([1, 1, 1, 1], [0, 0, 0,", "== bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2 -", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ...", ">>> [b.value for b in bs] [1, 1, 1, 0,", "0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ...", "= output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "1] >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))]", "(x, y) in zip(self, other)]) def nimp_(self: bits, other: bits)", "return bits([x.and_(y) for (x, y) in zip(self, other)]) def nimp(self:", "the function as an attribute. bit.circuit(circuit()) args_in = { k:", "__or__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "For forward-compatibility with PEP 563. eval_ = lambda a: eval(a)", ">>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1,", "\"\"\" return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def", "xys] [[1], [0], [0], [1]] >>> @synthesize ... def conjunction(xy:", ">>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0], [1]]", "circuit synthesis failed \"\"\" # Functions for determining types/signature from", "= output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1,", "= output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "(x, y) in [(0, 0), (0, 1), (1, 0), (1,", "-> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in", "def xnor_(self: bits, other: bits) -> bits: \"\"\" >>> results", "for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1,", "zs = outputs(xs ^ ys) ... ns = [int(z) for", "for (x, y) in zip(self, other)]) def nif_(self: bits, other:", "other) def nimp_(self, other): \"\"\" >>> results = [] >>>", "y) in zip(self, other)]) def xor_(self: bits, other: bits) ->", "output or whether there are others dependent on it. if", "0], [1, 1]] >>> @synthesize ... def equal(x, y): ...", "return bits([x.not_() for x in self]) def __invert__(self: bits) ->", "*args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value", "other)]) def __mod__(self, other) -> bits: \"\"\" >>> results =", "it returns an output. if bit._hook_operation is not None: r", "circuit built up out of those operators. >>> bit.hook_operation(lambda o,", "return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>> results", "@staticmethod def from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_)", "... results.append(ns == c.evaluate([x, x, x])) >>> all(results) True \"\"\"", "__init__(self: bit, value: int): self.value = value self.gate = bit._circuit.gate(op.id_,", "bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>> results =", "all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other):", "True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results", "a variable input from one source.\"\"\" class input_two(input): \"\"\"Bit that", "self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) % input(y)) ...", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ...", "0: b = ~(~b) # Preserve the bit by copying", "b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True", "... b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys))", "def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for", "import doctest from parts import parts from circuit import op,", "0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ...", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) ==", "in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>>", "for (x, y) in zip(self, other)]) def nimp_(self: bits, other:", "... def hook(o, v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate", "zs] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x,", "lambda a: output if a is bit else outputs #", "Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) ->", "Sequence of lengths. elif isinstance(other, set) and len(other) == 1", "def __or__(self, other): \"\"\" >>> results = [] >>> for", "bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is designated as", "DSL for assembling logic circuits. Embedded domain-specific combinator library for", "return self ^ (constant(other) if isinstance(other, int) else other) def", "'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit", "zip(self, other)]) def nor_(self: bits, other: bits) -> bits: \"\"\"", "in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit =", "bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", ">>> all(results) True \"\"\" return self.nimp(other) def nif(self, other): \"\"\"", "y])) ... zs = outputs(xs > ys) ... ns =", "results.append(ns == c.evaluate([x, x, x])) >>> all(results) True \"\"\" return", "output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other):", "y, y])) >>> all(results) True \"\"\" return bits([x.and_(y) for (x,", "b2=None): # The inference code below is not currently in", ">>> bs = bs << 3 >>> [b.value for b", "def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for", "> 0 and isinstance(other[0], int): return map(bits, parts(self, length=other)) #", "y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys]", "bits) -> bits: \"\"\" >>> results = [] >>> for", "= output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\"", "imp(self: bits, other: bits) -> bits: \"\"\" >>> results =", "y) in zip(self, other)]) def __le__(self: bits, other: bits) ->", "0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): #", "\"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>>", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_,", "in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1, 1]", "bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1, 1] >>>", "vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit)", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>>", "(0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b", "(x, y) in zip(self, other)]) def if_(self: bits, other: bits)", "def constructor(b1, b2=None): # The inference code below is not", "in bs] for bs in bss] [[1, 1], [1, 1],", "... zs = outputs(xs & ys) ... ns = [int(z)", "| ys) ... ns = [int(z) for z in zs]", "/ 2) >>> ([b.value for b in bss[0]], [b.value for", "0] \"\"\" def __init__(self: bit, b: bit): # Check if", "\"\"\" return bits([x.if_(y) for (x, y) in zip(self, other)]) def", "all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other):", "0, 0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for", "from a second source.\"\"\" class output(bit): \"\"\" Bit that is", "inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns =", "... b = output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>>", "\"\"\" # Functions for determining types/signature from # the type", "True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\"", "(x, y) in zip(self, other)]) def nor_(self: bits, other: bits)", "0, 0, 0, 0, 0, 0, 0] \"\"\" return bits(self[other:])", "nimp_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "is designated as a variable input from one source.\"\"\" class", "for y in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n)", "[1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>> ([b.value for", "[a.gate for a in args])) ... return hook >>> bit.hook_operation(make_hook(bit))", "bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>> results =", "__lt__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\"", "self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903", "bit by copying it to a new wire. self.value =", "... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "\"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>>", "self, other) def nor_(self, other): \"\"\" >>> results = []", "outputs(xs >= ys) ... ns = [int(z) for z in", "class input(bit): \"\"\"Bit that is designated as a variable input.\"\"\"", "@staticmethod def operation(o, *args): # Ensure second argument is a", "@staticmethod def from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>>", "# Sequence of lengths. elif isinstance(other, set) and len(other) ==", "given the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int)", "for automatically synthesizing a circuit from a function that takes", "a) type_out = lambda a: output if a is bit", "... zs = outputs(xs >= ys) ... ns = [int(z)", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y)))", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def xor(self, other):", "(x, y) in zip(self, other)]) def imp(self: bits, other: bits)", "bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs =", "bits(map(input, l)) def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\"", "Functions for determining types/signature from # the type annotation of", "True >>> def make_hook(bit_): ... def hook(o, v, *args): ...", "bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>>", "constant(1) >>> b.value 0 \"\"\" return self & (constant(other) if", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b)", "output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 =", "= bit._circuit.gate() if gate_ is None else gate_ def __int__(self):", ">>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self,", "0] \"\"\" return bits([ bit_ for byte_ in bytes_ for", "= output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "other) def __le__(self, other): \"\"\" >>> results = [] >>>", "y, y, y])) >>> all(results) True \"\"\" return bits([x.if_(y) for", "** bits([constant(0) for _ in range(other)]) def __truediv__(self: bits, other)", "def make_hook(bit_): ... def hook(o, v, *args): ... return bit_.constructor(*args)(v,", "y) in zip(self, other)]) def nimp_(self: bits, other: bits) ->", "b) in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\"", "output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return", "type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k != 'return'", "-> bits: \"\"\" >>> results = [] >>> for x", "y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns = [int(z)", "& xy[1]) >>> xys = [bits([x, y]) for x in", "combinator library for assembling abstract definitions of logic circuits and", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def", "= output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit =", "y) in zip(self, other)]) def nor(self: bits, other: bits) ->", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ...", "for (x, y) in zip(self, other)]) def xor(self: bits, other:", "or_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True", "bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nimp_(self: bits,", "... zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for z", "to the function as an attribute. bit.circuit(circuit()) args_in = {", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ...", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b)", "y])) ... zs = outputs(xs <= ys) ... ns =", "bss = list(bs / {2}) >>> [[b.value for b in", "= output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None)", "x in [0, 1]: ... bit.circuit(circuit()) ... xs = inputs([x,", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys))", "\"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>>", "x, x]), inputs([y, y, y])) ... zs = outputs(xs %", "y, y, y])) >>> all(results) True \"\"\" return bits([x.or_(y) for", "result of the operation on the arguments. v = o(*[a.value", "constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b", "b = output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "self, other) def __mod__(self, other): \"\"\" >>> results = []", "def nif_(self, other): \"\"\" >>> results = [] >>> for", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) ==", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ...", "bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0,", "@synthesize ... def equal(x, y): ... return x & y", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b)", "... b = output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "is None: return type(b1) else: return bit \"\"\" return bit", "b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "y])) ... zs = outputs(xs ^ ys) ... ns =", "xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for", "y, y])) ... zs = outputs(xs > ys) ... ns", "outputs(xs < ys) ... ns = [int(z) for z in", "inputs([y, y, y])) ... zs = outputs(xs == ys) ...", "return bits([x.or_(y) for (x, y) in zip(self, other)]) def __or__(self:", "inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ... ns =", "zip(self, other)]) def nimp_(self: bits, other: bits) -> bits: \"\"\"", "in zip(self, other)]) def __eq__(self: bits, other: bits) -> bits:", "vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits,", "bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results = [] >>>", ">>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __or__(self,", "y])) ... zs = outputs(xs.if_(ys)) ... ns = [int(z) for", "other)]) def nif(self: bits, other: bits) -> bits: \"\"\" >>>", "... zs = outputs(xs.xnor_(ys)) ... ns = [int(z) for z", "... zs = outputs(xs.nor(ys)) ... ns = [int(z) for z", "all(results) True \"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other):", "= outputs(xs.or_(ys)) ... ns = [int(z) for z in zs]", "second source.\"\"\" class output(bit): \"\"\" Bit that is designated an", "1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0],", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b)", "as a variable input from a second source.\"\"\" class output(bit):", "designated as a constant input.\"\"\" class input(bit): \"\"\"Bit that is", "recent call last): ... ValueError: can only subtract a bit", "reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit)", "for representing a vector of abstract bits. \"\"\" @staticmethod def", "= output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "xy in xys] [[1], [0], [0], [1]] >>> @synthesize ...", "output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args): # Ensure", "output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return", "return bits([x.xor_(y) for (x, y) in zip(self, other)]) def xor_(self:", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def", "[1, 3, 4]) >>> [[b.value for b in bs] for", "int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3)", "True \"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)])", "y) in zip(self, other)]) def nif_(self: bits, other: bits) ->", "x in self]) def and_(self: bits, other: bits) -> bits:", "inference code below is not currently in use. \"\"\" if", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x)", "only `bit` and/or `bits` objects as its arguments and returns", "all(results) True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other):", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) ==", "= (inputs([x, x, x]), inputs([y, y, y])) ... zs =", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3", "circuit(circuit_=None): if circuit_ is not None: bit._circuit = circuit_ return", "zs = outputs(xs < ys) ... ns = [int(z) for", "bits([x.nor_(y) for (x, y) in zip(self, other)]) def nor_(self: bits,", ">>> results = [] >>> for (x, y) in [(0,", "inputs([y, y, y])) ... zs = outputs(xs <= ys) ...", "circuit_ is not None: bit._circuit = circuit_ return None else:", "other)]) def __or__(self: bits, other: bits) -> bits: \"\"\" >>>", "^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\"", "in self]) def __invert__(self: bits) -> bits: \"\"\" >>> results", "x]) ... ys = outputs(xs.not_()) ... ns = [int(y) for", "(0, 1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for", "b = ~(~b) # Preserve the bit by copying it", "b.value 1 \"\"\" return self ^ (constant(other) if isinstance(other, int)", "return bits([x.nor_(y) for (x, y) in zip(self, other)]) def xnor(self:", "lambda a: eval(a) if isinstance(a, str) else a # pylint:", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for", "zs = outputs(xs >= ys) ... ns = [int(z) for", "b in bs] for bs in bss] [[1], [1, 1,", "bit.circuit(circuit()) ... b = output(input(x) < input(y)) ... results.append(int(b) ==", "x, x]), inputs([y, y, y])) ... zs = outputs(xs &", "= bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y, y,", "list(bs / [1, 3, 4]) >>> [[b.value for b in", "except: raise RuntimeError('automated circuit synthesis failed') from None # Return", "as a variable input from one source.\"\"\" class input_two(input): \"\"\"Bit", "from circuit import op, gate, circuit, signature class bit(): \"\"\"", "for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in", "return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\" >>> results", "bs = bs << 3 >>> [b.value for b in", "isinstance(a, str) else a # pylint: disable=W0123 try: # Construct", "inputs([y, y, y])) ... zs = outputs(xs >= ys) ...", "return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self,", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b)", "[1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs", "bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>> results =", "{2}) >>> [[b.value for b in bs] for bs in", "or_(self, other): \"\"\" >>> results = [] >>> for (x,", "other) def __ge__(self, other): \"\"\" >>> results = [] >>>", "constants(l): return bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def", "inputs([x, x, x]) ... ys = outputs(xs.not_()) ... ns =", ">>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>> ys", "if bit._hook_operation is not None: r = bit._hook_operation(o, v, *args)", "k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k !=", "[(0, 0), (0, 1), (1, 0), (1, 1)]: ... bit.circuit(circuit())", "bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits)", "(xy[0], xy[0] & xy[1]) >>> xys = [bits([x, y]) for", "bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent call last):", "def __and__(self: bits, other: bits) -> bits: \"\"\" >>> results", "... xs = inputs([x, x, x]) ... ys = outputs(~xs)", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) % input(y))", ">>> bs = bs >> 3 >>> [b.value for b", "else args[1] # Compute the value of the result of", "all(results) True \"\"\" return bit.operation(op.imp_, self, other) def nand(self, other):", "0, 1, 1, 0, 0, 0, 0, 0, 0, 0,", "def not_(self): \"\"\" >>> results = [] >>> for x", "b = output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "that is designated as a variable input from a second", "([1, 1, 1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit())", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b =", "... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "bss = list(bs / [1, 3, 4]) >>> [[b.value for", "[0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b)", "= outputs(xs & ys) ... ns = [int(z) for z", "[1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3, 4]) >>>", "logic circuits and synthesizing circuits from those definitions. \"\"\" from", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self,", "... zs = outputs(xs > ys) ... ns = [int(z)", "b = output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "all(results) True \"\"\" return self.nimp(other) def nif(self, other): \"\"\" >>>", ">>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0]", "bits([x.nand_(y) for (x, y) in zip(self, other)]) def nand_(self: bits,", "in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>>", "0]))] [0, 0, 0, 0, 1, 0, 1, 1, 0,", "bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ... return hook", "other) class constant(bit): \"\"\"Bit that is designated as a constant", "a new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate],", "y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for (x,", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) ==", "bit, y: bit) -> bit: ... return (x & y)", "a bit can be interpreted concretely as a value, but", "= None) -> bits: \"\"\" Return bits object given the", "... b = output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "bits([constant(0) for _ in range(other)]) def __truediv__(self: bits, other) ->", "True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)])", "b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o,", "return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def __gt__(self:", "def __new__(cls, argument = None) -> bits: \"\"\" Return bits", "y, y])) ... zs = outputs(xs == ys) ... ns", "y) in zip(self, other)]) def nand_(self: bits, other) -> bits:", "} type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis", "in xys] [[1], [0], [0], [1]] >>> @synthesize ... def", "0, 0, 0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0)", "output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "... ns = [int(y) for y in ys] ... c", "all(results) True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other):", "b2.value] [0, 1, 0] \"\"\" def __init__(self: bit, b: bit):", "*args): # Ensure second argument is a `bit`. args =", "ValueError: can only subtract a bit from the integer 1", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) > input(y))", "output. if bit._hook_operation is not None: r = bit._hook_operation(o, v,", "zs = outputs(xs == ys) ... ns = [int(z) for", "self]) def __invert__(self: bits) -> bits: \"\"\" >>> results =", "def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1", "return bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>> results", "... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>> results =", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y)))", "x in self]) def __invert__(self: bits) -> bits: \"\"\" >>>", "= output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value, b2.value]", "y])) ... zs = outputs(xs.xnor(ys)) ... ns = [int(z) for", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self, other)", "1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for b in", "all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in zip(self,", "constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7", "x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ... ns", "= b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): #", "all(results) True \"\"\" return bits([x.not_() for x in self]) def", "- input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>>", "output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "object given the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument,", ">>> for x in [0, 1]: ... bit.circuit(circuit()) ... b", ">>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >>", "& (1 - y)) >>> xys = [bits([x, y]) for", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>> [b.value", "xor_(self, other): \"\"\" >>> results = [] >>> for (x,", "def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0", "True \"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)])", ">>> @synthesize ... def equal(x: bit, y: bit) -> bit:", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) & input(y)) ...", "other) def xnor_(self, other): \"\"\" >>> results = [] >>>", "all(results) True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit", "other == 1: return bit.operation(op.not_, self) raise ValueError('can only subtract", "bits([x.nif_(y) for (x, y) in zip(self, other)]) def xor(self: bits,", "in bs] [0, 0, 0, 1, 1, 1, 1, 0]", "is `other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation of", "y, y])) ... zs = outputs(xs ^ ys) ... ns", "3 >>> [b.value for b in bs] [0, 0, 0,", "b.value 1 \"\"\" return self | (constant(other) if isinstance(other, int)", "dependent on it. if len(b.gate.outputs) > 0: b = ~(~b)", "... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x,", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y)", "# Compute the value of the result of the operation", "= outputs(xs.nand(ys)) ... ns = [int(z) for z in zs]", "output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "zip(self, other)]) def __gt__(self: bits, other: bits) -> bits: \"\"\"", "bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>> results =", "[0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "all(results) True \"\"\" return bits([x.nimp_(y) for (x, y) in zip(self,", "function decorated for automated synthesis. \"\"\" class bits(list): \"\"\" Class", "len(b.gate.outputs) > 0: b = ~(~b) # Preserve the bit", "... zs = outputs(xs.xor_(ys)) ... ns = [int(z) for z", "y])) >>> all(results) True \"\"\" return bits([x.and_(y) for (x, y)", "c.evaluate([x, x, x, y, y, y])) >>> all(results) True \"\"\"", "x]), inputs([y, y, y])) ... zs = outputs(xs % ys)", "outputs(xs == ys) ... ns = [int(z) for z in", "bss[0]], [b.value for b in bss[1]]) ([1, 1, 1, 1],", ">>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self,", "if # it returns an output. if bit._hook_operation is not", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other) def xor(self,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def", "[0, 0, 0, 0, 1, 0, 1, 1, 0, 0,", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.or_(ys)) ...", "all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self,", "bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs", "__lshift__(self: bits, other) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs", "def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args): #", "operator: rotation and shift operations. >>> bit.circuit(circuit()) >>> bs =", "c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>>", "bits([x.and_(y) for (x, y) in zip(self, other)]) def nimp(self: bits,", "as a constant input.\"\"\" class input(bit): \"\"\"Bit that is designated", "zip(self, other)]) def nif_(self: bits, other: bits) -> bits: \"\"\"", "[0, 0, 0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit())", "RuntimeError: automated circuit synthesis failed \"\"\" # Functions for determining", "x in [0, 1]: ... bit.circuit(circuit()) ... b = output(1", "= inputs([x, x, x]) ... ys = outputs(xs.not_()) ... ns", "return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>> results", "... return (x & y) | ((1 - x) &", "... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "its arguments and returns an output of type `bit` or", "True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\"", "an output. if bit._hook_operation is not None: r = bit._hook_operation(o,", "= bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated as", "a circuit built up out of those operators. >>> bit.hook_operation(lambda", "zip(self, other)]) def nif(self: bits, other: bits) -> bits: \"\"\"", "bit.circuit() ... results.append(ns == c.evaluate([x, x, x])) >>> all(results) True", "(x, y) in zip(self, other)]) def __rshift__(self: bits, other) ->", "y)) >>> xys = [bits([x, y]) for x in (0,", ">>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self,", "bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i", "True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\"", ">>> all(results) True \"\"\" return bits([x.and_(y) for (x, y) in", "... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b =", "= list(bs / 2) >>> ([b.value for b in bss[0]],", "bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>> b =", "can be interpreted concretely as a value, but it is", "in args])) @staticmethod def constructor(b1, b2=None): # The inference code", "function. type_in = lambda a: input(0) if a is bit", ">>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0,", "bits([x.nif_(y) for (x, y) in zip(self, other)]) def nif_(self: bits,", "bit else outputs # For forward-compatibility with PEP 563. eval_", "= output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "\"\"\" return bits([x.or_(y) for (x, y) in zip(self, other)]) def", "= bs >> 3 >>> [b.value for b in bs]", "True \"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)])", "return bits([x.if_(y) for (x, y) in zip(self, other)]) def imp(self:", "list) and len(other) > 0 and isinstance(other[0], int): return map(bits,", "int): return self / (len(self)//list(other)[0]) # Parts of length `other`.", "\"\"\" Bit that is designated an output. >>> bit.circuit(circuit()) >>>", "inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ... ns =", "and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two) and isinstance(b2,", "0, 0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _", "as final output or whether there are others dependent on", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b)", "1: return bit.operation(op.not_, self) raise ValueError('can only subtract a bit", "True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\"", "y) in zip(self, other)]) def __lt__(self: bits, other: bits) ->", "as a value, but it is also used to keep", "Return output from hook if it exists and if #", "for _ in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]:", "b in bs] for bs in bss] [[1, 1], [1,", "input_two elif isinstance(b1, (input_one, input_two)) and b2 is None: return", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ...", "quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift", "from those definitions. \"\"\" from __future__ import annotations from typing", "def xor(self, other): \"\"\" >>> results = [] >>> for", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b)", "y])) ... zs = outputs(xs.nor_(ys)) ... ns = [int(z) for", "in zip(self, other)]) def xnor(self: bits, other: bits) -> bits:", "import annotations from typing import Sequence import doctest from parts", "list(bs / {2}) >>> [[b.value for b in bs] for", "equal(x: bit, y: bit) -> bit: ... return (x &", "assembling logic circuits. Embedded domain-specific combinator library for assembling abstract", "y) in zip(self, other)]) def xnor(self: bits, other: bits) ->", "len(other) > 0 and isinstance(other[0], int): return map(bits, parts(self, length=other))", "by copying it to a new wire. self.value = b.value", "in zip(self, other)]) def xor(self: bits, other: bits) -> bits:", "return bits([x.nor_(y) for (x, y) in zip(self, other)]) def __mod__(self,", "in bytes_ for bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def", "(xs, ys) = (inputs([x, x, x]), inputs([y, y, y])) ...", "__mod__(self, other) -> bits: \"\"\" >>> results = [] >>>", "operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs", ">>> [b.value for b in bs] [1, 0, 0, 0,", "def and_(self: bits, other: bits) -> bits: \"\"\" >>> results", "y) in zip(self, other)]) def __rshift__(self: bits, other) -> bits:", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ...", "... b = output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "designated as a variable input from one source.\"\"\" class input_two(input):", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) ==", "True \"\"\" return bits([x.not_() for x in self]) def and_(self:", "return bits([x.imp_(y) for (x, y) in zip(self, other)]) def __le__(self:", "\"\"\" return bit.operation(op.if_, self, other) def __ge__(self, other): \"\"\" >>>", "f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit()", "bits([x.if_(y) for (x, y) in zip(self, other)]) def __ge__(self: bits,", "outputs(xs.imp_(ys)) ... ns = [int(z) for z in zs] ...", "... zs = outputs(xs < ys) ... ns = [int(z)", "is also used to keep track of relationships between operators", "for assembling abstract definitions of logic circuits and synthesizing circuits", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_,", "return bits([ bit_ for byte_ in bytes_ for bit_ in", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.imp(ys))", "1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0,", "\"\"\" if isinstance(other, list) and len(other) > 0 and isinstance(other[0],", "isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one,", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ...", "0 \"\"\" return self & (constant(other) if isinstance(other, int) else", "value, but it is also used to keep track of", "forward-compatibility with PEP 563. eval_ = lambda a: eval(a) if", "@synthesize ... def equal(x: bit, y: bit) -> bit: ...", ">>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def xor_(self,", "\"\"\" _circuit = None _hook_operation = None @staticmethod def circuit(circuit_=None):", "elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1,", "... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0])", "return input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two", "y, y, y])) >>> all(results) True \"\"\" return bits([x.and_(y) for", "inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ... ns =", "used to keep track of relationships between operators and to", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for", "return type(b1) else: return bit \"\"\" return bit @staticmethod def", "return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def xnor_(self:", "other)]) def nimp(self: bits, other: bits) -> bits: \"\"\" >>>", "bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value ==", "y])) ... zs = outputs(xs.nif(ys)) ... ns = [int(z) for", "xs = inputs([x, x, x]) ... ys = outputs(xs.not_()) ...", "bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k, a) in", "self, other) def nand_(self, other): \"\"\" >>> results = []", "bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def outputs(l): return", "bit(): \"\"\" Class for representing an abstract bit. Such a", ">>> xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value", "... b = output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class", "= [] >>> for x in [0, 1]: ... bit.circuit(circuit())", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) %", "int) else\\ list.__new__(cls, argument) def __int__(self: bits) -> int: \"\"\"", "bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3} >>> [b.value", "return bits(map(input, l)) def outputs(l): return bits(map(output, l)) def synthesize(f):", "* a) type_out = lambda a: output if a is", "\"\"\"Bit that is designated as a variable input.\"\"\" def __init__(self:", "xnor_(self, other): \"\"\" >>> results = [] >>> for (x,", "Class for representing an abstract bit. Such a bit can", "\"\"\" if other == 1: return bit.operation(op.not_, self) raise ValueError('can", "from # the type annotation of the decorated function. type_in", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y)))", "def operation(o, *args): # Ensure second argument is a `bit`.", "(input_one, input_two)) and b2 is None: return type(b1) else: return", "b = output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "def not_(self: bits) -> bits: \"\"\" >>> results = []", "abstract definitions of logic circuits and synthesizing circuits from those", "@staticmethod def circuit(circuit_=None): if circuit_ is not None: bit._circuit =", "from parts import parts from circuit import op, gate, circuit,", "\"\"\" return self ^ (constant(other) if isinstance(other, int) else other)", "__and__(self: bits, other: bits) -> bits: \"\"\" >>> results =", ">>> all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other):", "arguments and returns an output of type `bit` or `bits`.", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b) ==", "only subtract a bit from the integer 1 \"\"\" if", "self, other) def xnor_(self, other): \"\"\" >>> results = []", "type `bit` or `bits`. >>> @synthesize ... def equal(x: bit,", "ys = outputs(~xs) ... ns = [int(y) for y in", "xy[1]) >>> xys = [bits([x, y]) for x in (0,", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) ==", "for (x, y) in zip(self, other)]) def __lt__(self: bits, other:", "... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "= 0 & constant(1) >>> b.value 0 \"\"\" return self", "\"\"\" return bits([constant(0)]*n) def __new__(cls, argument = None) -> bits:", "self, other) def nimp_(self, other): \"\"\" >>> results = []", "[b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1,", "b = output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "for z in zs] ... c = bit.circuit() ... results.append(ns", "zs = outputs(xs.imp(ys)) ... ns = [int(z) for z in", ">>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self,", "__new__(cls, argument = None) -> bits: \"\"\" Return bits object", "bits([x.not_() for x in self]) def and_(self: bits, other: bits)", "= outputs(xs.and_(ys)) ... ns = [int(z) for z in zs]", "other) def nand_(self, other): \"\"\" >>> results = [] >>>", "function. return f if __name__ == \"__main__\": doctest.testmod() # pragma:", "\"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>>", "= ~(~b) # Preserve the bit by copying it to", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_,", "= 1 | constant(0) >>> b.value 1 \"\"\" return self", "b1 = output(b0.not_()) >>> b2 = output(b0) >>> [b0.value, b1.value,", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys))", "(x, y) in zip(self, other)]) def __or__(self: bits, other: bits)", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y)))", "... bit.circuit(circuit()) ... b = output(input(x) > input(y)) ... results.append(int(b)", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.and_(y)", "return bit.operation(op.and_, self, other) def __and__(self, other): \"\"\" >>> results", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys))", "relationships between operators and to represent the wires within a", "other)]) def nif_(self: bits, other: bits) -> bits: \"\"\" >>>", ">>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1,", "return bit.operation(op.nif_, self, other) def nif_(self, other): \"\"\" >>> results", "(x, y) in zip(self, other)]) def __lt__(self: bits, other: bits)", "inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ... ns =", "return self.nimp(other) def nif(self, other): \"\"\" >>> results = []", "other)]) def nor_(self: bits, other: bits) -> bits: \"\"\" >>>", "isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int): return", "other) def nif_(self, other): \"\"\" >>> results = [] >>>", "... return x & y Traceback (most recent call last):", "equal(x, y): ... return x & y Traceback (most recent", "for (i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits) ->", ">>> [b.value for b in bs] [0, 0, 0, 1,", "\"\"\" from __future__ import annotations from typing import Sequence import", "designated as a variable input from a second source.\"\"\" class", "def equal(x: bit, y: bit) -> bit: ... return (x", "return bits(map(constant, l)) def inputs(l): return bits(map(input, l)) def outputs(l):", "return bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>> results", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ...", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for", "bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>>", "& input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "for a in args])) @staticmethod def constructor(b1, b2=None): # The", "self, other) def __ge__(self, other): \"\"\" >>> results = []", "= list(args) if len(args) == 2: args[1] = constant(args[1]) if", "output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def", "inputs([y, y, y])) ... zs = outputs(xs < ys) ...", "bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>> results =", "other) def xnor(self, other): \"\"\" >>> results = [] >>>", "@staticmethod def constructor(b1, b2=None): # The inference code below is", "value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is", "(constant(other) if isinstance(other, int) else other) def or_(self, other): \"\"\"", "= outputs(xs.imp(ys)) ... ns = [int(z) for z in zs]", "other)]) def if_(self: bits, other: bits) -> bits: \"\"\" >>>", "\"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results", "1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value", "ns = [int(y) for y in ys] ... c =", ">>> all(results) True \"\"\" return bits([x.nand_(y) for (x, y) in", "other) def __gt__(self, other): \"\"\" >>> results = [] >>>", ">>> all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback", "below is not currently in use. \"\"\" if isinstance(b1, input_one)", "return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args]))", "bit.circuit(circuit()) >>> b = 0 & constant(1) >>> b.value 0", "self, other) def imp_(self, other): \"\"\" >>> results = []", "__matmul__(self, other): \"\"\" >>> results = [] >>> for (x,", "= outputs(xs > ys) ... ns = [int(z) for z", "outputs(xs.nif_(ys)) ... ns = [int(z) for z in zs] ...", "= outputs(xs | ys) ... ns = [int(z) for z", "bit vectors.\"\"\" return self + other def constants(l): return bits(map(constant,", "nimp(self: bits, other: bits) -> bits: \"\"\" >>> results =", "(constant(other) if isinstance(other, int) else other) def nor(self, other): \"\"\"", "... bit.circuit(circuit()) ... b = output(input(x) == input(y)) ... results.append(int(b)", "zs = outputs(xs > ys) ... ns = [int(z) for", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @", "y])) ... zs = outputs(xs.xor(ys)) ... ns = [int(z) for", "2 - input(0) Traceback (most recent call last): ... ValueError:", "True \"\"\" return bit.operation(op.if_, self, other) def imp(self, other): \"\"\"", "(0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1], [0],", "output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 = output(b0) >>>", "y])) ... zs = outputs(xs.nand(ys)) ... ns = [int(z) for", "= outputs(xs.imp_(ys)) ... ns = [int(z) for z in zs]", "y) in zip(self, other)]) def imp(self: bits, other: bits) ->", "bit_ for byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor)", "takes only `bit` and/or `bits` objects as its arguments and", "in bs] for bs in bss] [[1], [1, 1, 1],", "is a `bit`. args = list(args) if len(args) == 2:", "of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) ->", "= outputs(xs.if_(ys)) ... ns = [int(z) for z in zs]", "on it. if len(b.gate.outputs) > 0: b = ~(~b) #", "bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod", "circuit, signature class bit(): \"\"\" Class for representing an abstract", "return bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>> results", "y in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def", "bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>> results =", "the operation on the arguments. v = o(*[a.value for a", "True \"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\"", "for automated synthesis. \"\"\" class bits(list): \"\"\" Class for representing", "and len(other) == 1 and isinstance(list(other)[0], int): return self /", "bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0)", "is designated as a variable input from a second source.\"\"\"", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_, self,", "True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other): \"\"\"", "bit.circuit(circuit()) ... b = output(input(x) <= input(y)) ... results.append(int(b) ==", "[1, 1, 1], [0, 0, 0, 0]] \"\"\" if isinstance(other,", "def __xor__(self, other): \"\"\" >>> results = [] >>> for", "\"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument) def", "True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\"", "results = [] >>> for (x, y) in [(0, 0),", "The inference code below is not currently in use. \"\"\"", "self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit", "True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\"", "self, other) def nand(self, other): \"\"\" >>> results = []", "y])) >>> all(results) True \"\"\" return bits([x.nif_(y) for (x, y)", "synthesis. \"\"\" class bits(list): \"\"\" Class for representing a vector", "the integer 1') def and_(self, other): \"\"\" >>> results =", "True \"\"\" return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\"", "... return (xy[0], xy[0] & xy[1]) >>> xys = [bits([x,", "value: int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class", "\"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is", "= [] >>> for (x, y) in [(0, 0), (0,", "\"\"\" return self | (constant(other) if isinstance(other, int) else other)", "return self / (len(self)//list(other)[0]) # Parts of length `other`. else:", "bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self,", "(x, y) in zip(self, other)]) def nif_(self: bits, other: bits)", "... bit.circuit(circuit()) ... b = output(input(x) | input(y)) ... results.append(int(b)", "b = 1 ^ constant(0) >>> b.value 1 \"\"\" return", "\"\"\" return bits([ bit_ for byte_ in bytes_ for bit_", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y)))", ">>> bit.hook_operation(lambda o, v, *args: None) >>> bit.circuit(circuit()) >>> b", "Check if bit is ready as final output or whether", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys))", "zs = outputs(xs <= ys) ... ns = [int(z) for", "= outputs(~xs) ... ns = [int(y) for y in ys]", "of parts is `other`. def __add__(self: bits, other) -> bits:", "... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0])", "in zs] ... c = bit.circuit() ... results.append(ns == c.evaluate([x,", "__eq__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "[bits([x, y]) for x in (0, 1) for y in", "Return bits object given the supplied argument. \"\"\" return bits_type(argument)\\", "y])) >>> all(results) True \"\"\" return bits([x.if_(y) for (x, y)", "... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "__le__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit()) >>>", "for xy in xys] [[0, 0], [0, 0], [1, 0],", "bit.circuit(circuit()) ... xs = inputs([x, x, x]) ... ys =", "bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ... results.append(int(b) ==", "all(results) True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self, other):", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b)", "return self + other def constants(l): return bits(map(constant, l)) def", "... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", ">>> xs = constants([0, 0, 0]) >>> ys = outputs(xs.not_())", "1 \"\"\" return self ^ (constant(other) if isinstance(other, int) else", "\"\"\" return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs)", "... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "zip(self, other)]) def if_(self: bits, other: bits) -> bits: \"\"\"", "eval_ = lambda a: eval(a) if isinstance(a, str) else a", "def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >= input(y))", "for (x, y) in zip(self, other)]) def __gt__(self: bits, other:", "x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ... ns", "vectors.\"\"\" return self + other def constants(l): return bits(map(constant, l))", ">>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self,", "1]] >>> @synthesize ... def equal(x, y): ... return x", "range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit())", "y])) ... zs = outputs(xs.nor(ys)) ... ns = [int(z) for", "bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit", "... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "nimp(self, other): \"\"\" >>> results = [] >>> for (x,", ">>> all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in", "2) >>> ([b.value for b in bss[0]], [b.value for b", "bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]), inputs([y, y,", "x & y Traceback (most recent call last): ... RuntimeError:", "bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>> results = []", ">>> all(results) True \"\"\" return bits([x.not_() for x in self])", "outputs(~xs) ... ns = [int(y) for y in ys] ...", "a value, but it is also used to keep track", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b)", "x]), inputs([y, y, y])) ... zs = outputs(xs > ys)", "second argument is a `bit`. args = list(args) if len(args)", "outputs(xs.if_(ys)) ... ns = [int(z) for z in zs] ...", "... b = output(input(x) > input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "(most recent call last): ... ValueError: can only subtract a", "zs = outputs(xs | ys) ... ns = [int(z) for", "zs = outputs(xs.nor(ys)) ... ns = [int(z) for z in", "Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit()) >>> bs", "_circuit = None _hook_operation = None @staticmethod def circuit(circuit_=None): if", "def __le__(self: bits, other: bits) -> bits: \"\"\" >>> results", "outputs # For forward-compatibility with PEP 563. eval_ = lambda", "y) in zip(self, other)]) def __ge__(self: bits, other: bits) ->", "def __add__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\"", "return bit.operation(op.nor_, self, other) def nor_(self, other): \"\"\" >>> results", "built up out of those operators. >>> bit.hook_operation(lambda o, v,", "other: bits) -> bits: \"\"\" >>> results = [] >>>", "zip(self, other)]) def __rshift__(self: bits, other) -> bits: \"\"\" Overloaded", "c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y,", "other)]) def imp(self: bits, other: bits) -> bits: \"\"\" >>>", "args[1] # Compute the value of the result of the", ">= ys) ... ns = [int(z) for z in zs]", "other) -> bits: \"\"\" Overloaded operator: rotation and shift operations.", "isinstance(b1, (input_one, input_two)) and b2 is None: return type(b1) else:", "= output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "1, 1, 0, 0, 0, 0, 1] \"\"\" if isinstance(other,", "add it to the function as an attribute. bit.circuit(circuit()) args_in", "bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod", "b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "xs = inputs([x, x, x]) ... ys = outputs(~xs) ...", "x, x]), inputs([y, y, y])) ... zs = outputs(xs |", "bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>> results =", "None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value ==", "if len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1], int)", "0, 0, 0] \"\"\" return bits([ bit_ for byte_ in", "other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self)", "self, other) def xor_(self, other): \"\"\" >>> results = []", "bs] for bs in bss] [[1, 1], [1, 1], [0,", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other) def", "\"\"\" >>> results = [] >>> for (x, y) in", "from a function that takes only `bit` and/or `bits` objects", "of those operators. >>> bit.hook_operation(lambda o, v, *args: None) >>>", "and returns an output of type `bit` or `bits`. >>>", "bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "synthesizing circuits from those definitions. \"\"\" from __future__ import annotations", "a in args]) # Return output from hook if it", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) < input(y))", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def", "an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1", "y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for (x, y)", "return input_two elif isinstance(b1, (input_one, input_two)) and b2 is None:", "= outputs(xs == ys) ... ns = [int(z) for z", ">>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0]", "... zs = outputs(xs.nand_(ys)) ... ns = [int(z) for z", "and shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "return self & (constant(other) if isinstance(other, int) else other) def", "# Parts of length `other`. else: return map(bits, parts(self, other))", "inputs([0] * a) type_out = lambda a: output if a", "1, 1] >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11,", "type of a function decorated for automated synthesis. \"\"\" class", "= output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_):", ">>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0], [0, 0],", "and synthesizing circuits from those definitions. \"\"\" from __future__ import", "*args) if r is not None: return r return bit.constructor(*args)(v,", "1, 0, 1, 1, 0, 0, 0, 0, 0, 0,", "= constant(args[1]) if isinstance(args[1], int) else args[1] # Compute the", "(x, y) in zip(self, other)]) def nor(self: bits, other: bits)", "in zip(self, other)]) def nif(self: bits, other: bits) -> bits:", "bs >> 3 >>> [b.value for b in bs] [0,", ">>> bss = list(bs / 2) >>> ([b.value for b", ">>> ([b.value for b in bss[0]], [b.value for b in", "\"\"\"Concatenation of bit vectors.\"\"\" return self + other def constants(l):", "l)) def outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator", "\"\"\" return bits([x.not_() for x in self]) def and_(self: bits,", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.xnor_(ys)) ...", "return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing", "bits: \"\"\" Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit())", "y])) ... zs = outputs(xs & ys) ... ns =", "bit.circuit(circuit()) ... b = output(1 - input(x)) ... results.append(int(b) ==", "bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs =", "in zip(self, other)]) def __ge__(self: bits, other: bits) -> bits:", "= output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "= outputs(xs.xor(ys)) ... ns = [int(z) for z in zs]", "output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "y, y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y) for", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs", "zs = outputs(xs.and_(ys)) ... ns = [int(z) for z in", "other) def __rand__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b =", "y, y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for", "zip(self, other)]) def __xor__(self: bits, other: bits) -> bits: \"\"\"", "return bits([x.xnor_(y) for (x, y) in zip(self, other)]) def if_(self:", "& (constant(other) if isinstance(other, int) else other) def nimp(self, other):", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self, other)", "map(bits, parts(self, length=other)) # Sequence of lengths. elif isinstance(other, set)", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ...", "zs = outputs(xs.nif(ys)) ... ns = [int(z) for z in", "zs = outputs(xs % ys) ... ns = [int(z) for", "domain-specific combinator library for assembling abstract definitions of logic circuits", "= list(self) result.extend(list(other)) return bits(result) def __pow__(self: bits, other) ->", "for assembling logic circuits. Embedded domain-specific combinator library for assembling", "call last): ... ValueError: can only subtract a bit from", "bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))]", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^", "return bits([x.nor_(y) for (x, y) in zip(self, other)]) def nor_(self:", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^ input(y))", "inputs([y, y, y])) ... zs = outputs(xs & ys) ...", "[1]] >>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2): ...", "<= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "= outputs(xs.nif_(ys)) ... ns = [int(z) for z in zs]", "None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in", "None @staticmethod def circuit(circuit_=None): if circuit_ is not None: bit._circuit", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor(input(y)))", "(x, y) in zip(self, other)]) def __xor__(self: bits, other: bits)", "assembling abstract definitions of logic circuits and synthesizing circuits from", "for (x, y) in zip(self, other)]) def or_(self: bits, other:", "only subtract a bit from the integer 1') def and_(self,", "def __int__(self): return self.value def not_(self): \"\"\" >>> results =", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b)", "... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "int) else args[1] # Compute the value of the result", "returns an output of type `bit` or `bits`. >>> @synthesize", "y, y])) >>> all(results) True \"\"\" return bits([x.or_(y) for (x,", "y) in zip(self, other)]) def __eq__(self: bits, other: bits) ->", "in bss[0]], [b.value for b in bss[1]]) ([1, 1, 1,", "# The inference code below is not currently in use.", "i in range(8)]) ]) @staticmethod def from_bytes(bytes_, constructor=bit) -> bits:", "True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\"", "= None _hook_operation = None @staticmethod def circuit(circuit_=None): if circuit_", "... RuntimeError: automated circuit synthesis failed \"\"\" # Functions for", "(x, y) in zip(self, other)]) def xor_(self: bits, other: bits)", "1), (1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys)", "output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "0], [0, 0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "x, x, y, y, y])) >>> all(results) True \"\"\" return", "bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2 for i in range(8)])", "zip(self, other)]) def __or__(self: bits, other: bits) -> bits: \"\"\"", "for b in bs] for bs in bss] [[1, 1],", "output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None", "results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_, self)", "= output(1 - input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results)", "in ys] ... c = bit.circuit() ... results.append(ns == c.evaluate([x,", "x]), inputs([y, y, y])) ... zs = outputs(xs < ys)", "hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>>", "# Functions for determining types/signature from # the type annotation", "x]), inputs([y, y, y])) ... zs = outputs(xs | ys)", "self | (constant(other) if isinstance(other, int) else other) def nor(self,", "y])) ... zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for", "v, *args): ... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in", "import parts from circuit import op, gate, circuit, signature class", "... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\" return bit.operation(op.not_,", "v = o(*[a.value for a in args]) # Return output", ">>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys = outputs(xs.not_())", "zip(self, other)]) def __lt__(self: bits, other: bits) -> bits: \"\"\"", "bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([255]))] [1, 1, 1,", "Decorator for automatically synthesizing a circuit from a function that", "\"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>>", "of relationships between operators and to represent the wires within", "in zip(self, other)]) def __lt__(self: bits, other: bits) -> bits:", "nif_(self, other): \"\"\" >>> results = [] >>> for (x,", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) ^ input(y)) ...", "Return the original function. return f if __name__ == \"__main__\":", "__init__(self, value, gate_=None): self.value = value self.gate = bit._circuit.gate() if", "(x, y) in zip(self, other)]) def xnor(self: bits, other: bits)", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3,", "input_one elif isinstance(b1, input_two) and isinstance(b2, input_two): return input_two elif", "y) in zip(self, other)]) def nimp(self: bits, other: bits) ->", "of length `other`. else: return map(bits, parts(self, other)) # Number", "bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>>", "... b = output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args])) @staticmethod", "other)]) def __eq__(self: bits, other: bits) -> bits: \"\"\" >>>", "Sequence import doctest from parts import parts from circuit import", "output if a is bit else outputs # For forward-compatibility", "all(results) True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self, other):", "[[b.value for b in bs] for bs in bss] [[1,", "all(results) True \"\"\" return bits([x.xor_(y) for (x, y) in zip(self,", ">>> b.value 0 \"\"\" return self & (constant(other) if isinstance(other,", "lengths. elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0],", "isinstance(other, int) else other) def nimp(self, other): \"\"\" >>> results", "Ensure second argument is a `bit`. args = list(args) if", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ...", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y)))", "= bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\"", "outputs(xs.imp(ys)) ... ns = [int(z) for z in zs] ...", ">>> 2 - input(0) Traceback (most recent call last): ...", "\"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>>", "\"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys =", "zs = outputs(xs.nimp_(ys)) ... ns = [int(z) for z in", "self ^ (constant(other) if isinstance(other, int) else other) def or_(self,", "z in zs] ... c = bit.circuit() ... results.append(ns ==", "hook if it exists and if # it returns an", "\"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\" >>>", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) >= input(y)) ...", "def imp_(self: bits, other: bits) -> bits: \"\"\" >>> results", "annotation of the decorated function. type_in = lambda a: input(0)", "bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ...", ">>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation", "[1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls, argument =", "# Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else:", "= list(bs / {2}) >>> [[b.value for b in bs]", "__rsub__(self, other): \"\"\" >>> results = [] >>> for x", "automated synthesis. \"\"\" class bits(list): \"\"\" Class for representing a", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y)))", "isinstance(other, int) else other) def or_(self, other): \"\"\" >>> results", "gate_=None): self.value = value self.gate = bit._circuit.gate() if gate_ is", "bs = bs >> 3 >>> [b.value for b in", "... zs = outputs(xs.if_(ys)) ... ns = [int(z) for z", "True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other): \"\"\"", ">>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b) in", "b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "self.nimp(other) def nif(self, other): \"\"\" >>> results = [] >>>", "def __int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs", "y, y])) ... zs = outputs(xs.or_(ys)) ... ns = [int(z)", "else gate_ def __int__(self): return self.value def not_(self): \"\"\" >>>", "1]: ... bit.circuit(circuit()) ... xs = inputs([x, x, x]) ...", "inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output, l)) def", "1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy", "True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)])", "bits, other) -> bits: \"\"\" >>> results = [] >>>", "input_two): return input_two elif isinstance(b1, (input_one, input_two)) and b2 is", "\"\"\" return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>>", ">>> b = 0 & constant(1) >>> b.value 0 \"\"\"", "bits(list): \"\"\" Class for representing a vector of abstract bits.", "last): ... RuntimeError: automated circuit synthesis failed \"\"\" # Functions", "output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nif(other)", "... b = output(input(x) ^ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "self, other) def if_(self, other): \"\"\" >>> results = []", "= bs << 3 >>> [b.value for b in bs]", "all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other):", ">>> b.value 1 \"\"\" return self ^ (constant(other) if isinstance(other,", "zip(self, other)]) def xor(self: bits, other: bits) -> bits: \"\"\"", "y]) for x in (0, 1) for y in (0,", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ...", "in bss] [[1, 1], [1, 1], [0, 0], [0, 0]]", "type annotation of the decorated function. type_in = lambda a:", "0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "all(results) True \"\"\" return bit.operation(op.imp_, self, other) def imp_(self, other):", "outputs(xs.nor_(ys)) ... ns = [int(z) for z in zs] ...", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y))", "new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True)", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other)", "return self | (constant(other) if isinstance(other, int) else other) def", "| input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "map(bits, parts(self, other)) # Number of parts is `other`. def", "bit.circuit(circuit()) ... b = output(input(x) % input(y)) ... results.append(int(b) ==", "bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0,", "other)]) def imp_(self: bits, other: bits) -> bits: \"\"\" >>>", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >=", "y) in zip(self, other)]) def if_(self: bits, other: bits) ->", "__pow__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return", "y, y])) ... zs = outputs(xs.if_(ys)) ... ns = [int(z)", "`bit` and/or `bits` objects as its arguments and returns an", "def __mod__(self, other) -> bits: \"\"\" >>> results = []", "return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>> results", "return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\" >>> results", "= bit._hook_operation(o, v, *args) if r is not None: return", "__ge__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y)", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1, 3, 4])", "not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate for a", "or whether there are others dependent on it. if len(b.gate.outputs)", "is not None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable()", "other) def __xor__(self, other): \"\"\" >>> results = [] >>>", "isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:]) **", "original function. return f if __name__ == \"__main__\": doctest.testmod() #", "args[1] = constant(args[1]) if isinstance(args[1], int) else args[1] # Compute", "other) def imp(self, other): \"\"\" >>> results = [] >>>", "... bit.circuit(circuit()) ... b = output(input(x) & input(y)) ... results.append(int(b)", "output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "bits, other: bits) -> bits: \"\"\" >>> results = []", "x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ... ns", "([b.value for b in bss[0]], [b.value for b in bss[1]])", "[1, 1]] >>> @synthesize ... def equal(x, y): ... return", "a variable input.\"\"\" def __init__(self: bit, value: int): self.value =", "def circuit(circuit_=None): if circuit_ is not None: bit._circuit = circuit_", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2)", "b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1, 1,", "1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>> bs =", "bits([x.not_() for x in self]) def __invert__(self: bits) -> bits:", "self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b", "nand_(self: bits, other) -> bits: \"\"\" >>> results = []", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.if_(y)", "= outputs(xs >= ys) ... ns = [int(z) for z", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2})", "keep track of relationships between operators and to represent the", "bits([x.xor_(y) for (x, y) in zip(self, other)]) def __xor__(self: bits,", "bit.circuit(circuit()) ... b = output(input(x) > input(y)) ... results.append(int(b) ==", "self & (constant(other) if isinstance(other, int) else other) def nimp(self,", "b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def", "y): ... return x & y Traceback (most recent call", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self,", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) | input(y)) ...", "type_in = lambda a: input(0) if a is bit else", "nand(self, other): \"\"\" >>> results = [] >>> for (x,", "class constant(bit): \"\"\"Bit that is designated as a constant input.\"\"\"", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ...", "bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>> ys =", "circuits from those definitions. \"\"\" from __future__ import annotations from", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ...", "= outputs(xs.nif(ys)) ... ns = [int(z) for z in zs]", "\"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>>", "bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\"", "bits([ bit_ for byte_ in bytes_ for bit_ in bits.from_byte(byte_,", "bit.operation(op.nor_, self, other) def __mod__(self, other): \"\"\" >>> results =", "@staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def operation(o, *args):", "= outputs(xs.nimp_(ys)) ... ns = [int(z) for z in zs]", "return bits([x.nif_(y) for (x, y) in zip(self, other)]) def nif_(self:", "input.\"\"\" class input(bit): \"\"\"Bit that is designated as a variable", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ...", "igs) def __init__(self, value, gate_=None): self.value = value self.gate =", "** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def", "[0], [0], [1]] >>> @synthesize ... def conjunction(xy: bits(2)) ->", "other) -> bits: \"\"\" >>> results = [] >>> for", "y, y])) >>> all(results) True \"\"\" return bits([x.if_(y) for (x,", "of bit vectors.\"\"\" return self + other def constants(l): return", "subtract a bit from the integer 1') def and_(self, other):", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y)))", "= hook @staticmethod def operation(o, *args): # Ensure second argument", "abstract bits. \"\"\" @staticmethod def from_byte(byte_: int, constructor=bit) -> bits:", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_,", "ValueError('can only subtract a bit from the integer 1') def", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>> [[b.value", "if bit is ready as final output or whether there", "1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation.", "source.\"\"\" class input_two(input): \"\"\"Bit that is designated as a variable", ">>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most recent call", "\"\"\" return bits([x.imp_(y) for (x, y) in zip(self, other)]) def", "1 | constant(0) >>> b.value 1 \"\"\" return self |", "bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>>", ">>> all(results) True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self,", "other)) # Number of parts is `other`. def __add__(self: bits,", "__ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 |", "returns an output. if bit._hook_operation is not None: r =", "x]), inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ... ns", "y, y])) ... zs = outputs(xs < ys) ... ns", "... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) ==", "-> bits: \"\"\" Return bits object given the supplied argument.", "bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / [1,", "\"\"\" return self.nif(other) def xor(self, other): \"\"\" >>> results =", "Class for representing an input or output type of a", ">>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def xnor(self,", "[int(y) for y in ys] ... c = bit.circuit() ...", "for (x, y) in zip(self, other)]) def __rshift__(self: bits, other)", "f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from", "... ns = [int(z) for z in zs] ... c", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) >", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y)", "(x, y) in zip(self, other)]) def __eq__(self: bits, other: bits)", "length `other`. else: return map(bits, parts(self, other)) # Number of", "= output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "== 1: return bit.operation(op.not_, self) raise ValueError('can only subtract a", "nor_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "return bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def __truediv__(self:", "True \"\"\" return bit.operation(op.or_, self, other) def __or__(self, other): \"\"\"", "other) def __and__(self, other): \"\"\" >>> results = [] >>>", "\"\"\" >>> bit.circuit(circuit()) >>> xs = constants([0, 0, 0]) >>>", "= output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nor_, self,", "return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation", "# Return output from hook if it exists and if", "wire. self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class", "1)]: ... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]),", "synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit from a", "\"\"\" Decorator for automatically synthesizing a circuit from a function", "True \"\"\" _circuit = None _hook_operation = None @staticmethod def", "... bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "bit._hook_operation is not None: r = bit._hook_operation(o, v, *args) if", "def xor_(self, other): \"\"\" >>> results = [] >>> for", "def nimp_(self, other): \"\"\" >>> results = [] >>> for", "definitions. \"\"\" from __future__ import annotations from typing import Sequence", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y))) ... results.append(int(b)", "list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other)", "with PEP 563. eval_ = lambda a: eval(a) if isinstance(a,", "annotations from typing import Sequence import doctest from parts import", ">>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self,", "bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) -> bits: \"\"\"", "def nif(self, other): \"\"\" >>> results = [] >>> for", "return x & y Traceback (most recent call last): ...", "b = output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "zs = outputs(xs.nimp(ys)) ... ns = [int(z) for z in", "and_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "Class for representing a vector of abstract bits. \"\"\" @staticmethod", "= outputs(xs <= ys) ... ns = [int(z) for z", "def __mod__(self, other): \"\"\" >>> results = [] >>> for", "def nimp(self: bits, other: bits) -> bits: \"\"\" >>> results", "for bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod", "bits(2)) -> bits(2): ... return (xy[0], xy[0] & xy[1]) >>>", "| constant(0) >>> b.value 1 \"\"\" return self | (constant(other)", "other) def if_(self, other): \"\"\" >>> results = [] >>>", ">>> @synthesize ... def equal(x, y): ... return x &", "all(results) True \"\"\" return bit.operation(op.imp_, self, other) def __le__(self, other):", ">>> [y.value for y in ys] [1, 1, 1] \"\"\"", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ...", "function as an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a))", "\"\"\" return bits([x.xor_(y) for (x, y) in zip(self, other)]) def", "def __invert__(self: bits) -> bits: \"\"\" >>> results = []", "for (k, a) in f.__annotations__.items() if k != 'return' }", "[equal.circuit.evaluate(xy) for xy in xys] [[1], [0], [0], [1]] >>>", "of lengths. elif isinstance(other, set) and len(other) == 1 and", "for x in self]) def __invert__(self: bits) -> bits: \"\"\"", "[[1], [1, 1, 1], [0, 0, 0, 0]] \"\"\" if", "bit from the integer 1 \"\"\" if other == 1:", "b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "... zs = outputs(xs.xor(ys)) ... ns = [int(z) for z", "zip(self, other)]) def __le__(self: bits, other: bits) -> bits: \"\"\"", "x]), inputs([y, y, y])) ... zs = outputs(xs <= ys)", "class input_two(input): \"\"\"Bit that is designated as a variable input", "zs = outputs(xs.if_(ys)) ... ns = [int(z) for z in", "inputs([y, y, y])) ... zs = outputs(xs.xor(ys)) ... ns =", "<= ys) ... ns = [int(z) for z in zs]", "Number of parts is `other`. def __add__(self: bits, other) ->", "__rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^", "y, y])) ... zs = outputs(xs % ys) ... ns", "for b in bs] [1, 1, 1, 0, 0, 0,", "for (x, y) in zip(self, other)]) def __or__(self: bits, other:", "outputs(xs.or_(ys)) ... ns = [int(z) for z in zs] ...", "output(b0) >>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def", "others dependent on it. if len(b.gate.outputs) > 0: b =", "lambda a: input(0) if a is bit else inputs([0] *", "0 and isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence", "ys) = (inputs([x, x, x]), inputs([y, y, y])) ... zs", "an abstract bit. Such a bit can be interpreted concretely", "# Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other]) def __lshift__(self: bits, other)", "from None # Return the original function. return f if", "= list(other)[0] return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return", "... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b)", "a # pylint: disable=W0123 try: # Construct the circuit and", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >>", "bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ... results.append(int(b) ==", "all(results) True \"\"\" return bits([x.if_(y) for (x, y) in zip(self,", ">> 3 >>> [b.value for b in bs] [0, 0,", "all(results) True \"\"\" return bits([x.xnor_(y) for (x, y) in zip(self,", "3, 4]) >>> [[b.value for b in bs] for bs", "% ys) ... ns = [int(z) for z in zs]", "zip(self, other)]) def or_(self: bits, other: bits) -> bits: \"\"\"", "all(results) True >>> bit.circuit(circuit()) >>> 2 - input(0) Traceback (most", "__future__ import annotations from typing import Sequence import doctest from", "[0, 0, 0, 0]] \"\"\" if isinstance(other, list) and len(other)", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <= input(y))", "int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input):", "bit): # Check if bit is ready as final output", "str) else a # pylint: disable=W0123 try: # Construct the", "[1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>> [[b.value for", "len(other) == 1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0])", "in [0, 1]: ... bit.circuit(circuit()) ... b = output(1 -", "isinstance(other[0], int): return map(bits, parts(self, length=other)) # Sequence of lengths.", "self, other) def imp(self, other): \"\"\" >>> results = []", "\"\"\" Return bits object given the supplied argument. \"\"\" return", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs >> 3 >>> [b.value", "True \"\"\" return bits([x.nor_(y) for (x, y) in zip(self, other)])", "last): ... ValueError: can only subtract a bit from the", "\"\"\" class bits(list): \"\"\" Class for representing a vector of", "not_(self: bits) -> bits: \"\"\" >>> results = [] >>>", "\"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif", "!= 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated", "elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int):", "1, 0, 0, 0, 0, 0, 0, 0, 0] \"\"\"", "def imp_(self, other): \"\"\" >>> results = [] >>> for", "Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "... zs = outputs(xs.nif(ys)) ... ns = [int(z) for z", "that is designated as a variable input from one source.\"\"\"", "bits([x.nimp_(y) for (x, y) in zip(self, other)]) def __gt__(self: bits,", ">>> b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\"", "= output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", ">>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def nif_(self,", "outputs(xs.xor(ys)) ... ns = [int(z) for z in zs] ...", "0, 0] \"\"\" return bits(self[other:]) ** bits([constant(0) for _ in", "of the result of the operation on the arguments. v", "... c = bit.circuit() ... results.append(ns == c.evaluate([x, x, x]))", "other)]) def xor(self: bits, other: bits) -> bits: \"\"\" >>>", "= bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for y", "bits.zeros(3) >>> ys = outputs(xs.not_()) >>> [y.value for y in", "exists and if # it returns an output. if bit._hook_operation", ">>> all(results) True \"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self,", "self, other) def __eq__(self, other): \"\"\" >>> results = []", "... b = output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "y, y])) ... zs = outputs(xs.and_(ys)) ... ns = [int(z)", "of a function decorated for automated synthesis. \"\"\" class bits(list):", "{3} >>> [b.value for b in bs] [1, 1, 1,", "return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\" >>> results", "self, other) class constant(bit): \"\"\"Bit that is designated as a", "x, x]) ... ys = outputs(~xs) ... ns = [int(y)", "== input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "other) def or_(self, other): \"\"\" >>> results = [] >>>", "... b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "y])) ... zs = outputs(xs.imp(ys)) ... ns = [int(z) for", "eval(a) if isinstance(a, str) else a # pylint: disable=W0123 try:", "but it is also used to keep track of relationships", "((1 - x) & (1 - y)) >>> xys =", "Compute the value of the result of the operation on", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ...", "other) def imp_(self, other): \"\"\" >>> results = [] >>>", "inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ... ns =", "\"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs", "the bit by copying it to a new wire. self.value", "bs] [0, 0, 0, 1, 1, 1, 1, 0] >>>", "y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns = [int(z)", ">>> [[b.value for b in bs] for bs in bss]", "as an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for", "zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs =", "self) def __invert__(self): \"\"\" >>> results = [] >>> for", "for x in [0, 1]: ... bit.circuit(circuit()) ... xs =", "not None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <=", "int) else other) def nor(self, other): \"\"\" >>> results =", "other)]) def __le__(self: bits, other: bits) -> bits: \"\"\" >>>", "{ k: type_in(eval_(a)) for (k, a) in f.__annotations__.items() if k", "decorated for automated synthesis. \"\"\" class bits(list): \"\"\" Class for", "bit.circuit() ... results.append(ns == c.evaluate([x, x, x, y, y, y]))", "def __lt__(self: bits, other: bits) -> bits: \"\"\" >>> results", "bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result =", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y)))", "return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) **", "return bits([x.imp_(y) for (x, y) in zip(self, other)]) def nand(self:", ">>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>>", "zip(self, other)]) def __eq__(self: bits, other: bits) -> bits: \"\"\"", "in zip(self, other)]) def __and__(self: bits, other: bits) -> bits:", "__ge__(self, other): \"\"\" >>> results = [] >>> for (x,", "# it returns an output. if bit._hook_operation is not None:", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys))", "x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ... ns", "bit else inputs([0] * a) type_out = lambda a: output", "... zs = outputs(xs == ys) ... ns = [int(z)", "between operators and to represent the wires within a circuit", "operators and to represent the wires within a circuit built", "library for assembling abstract definitions of logic circuits and synthesizing", "constant(0) >>> b.value 1 \"\"\" return self | (constant(other) if", "if len(b.gate.outputs) > 0: b = ~(~b) # Preserve the", "... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "# Return the original function. return f if __name__ ==", "0, 1, 0, 1, 1, 0, 0, 0, 0, 0,", "... zs = outputs(xs.and_(ys)) ... ns = [int(z) for z", "circuit import op, gate, circuit, signature class bit(): \"\"\" Class", "zs = outputs(xs.nand_(ys)) ... ns = [int(z) for z in", "inputs([y, y, y])) ... zs = outputs(xs % ys) ...", "all(results) True \"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>>", "b = output(input(x) @ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "0, 0, 0, 0, 0, 0, 0] \"\"\" return bits([", "output of type `bit` or `bits`. >>> @synthesize ... def", "from hook if it exists and if # it returns", "zip(self, other)]) def __ge__(self: bits, other: bits) -> bits: \"\"\"", "b.value 0 \"\"\" return self & (constant(other) if isinstance(other, int)", ">>> results = [] >>> for x in [0, 1]:", "% input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs", "[0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "= outputs(xs.nor(ys)) ... ns = [int(z) for z in zs]", "self, other) def xnor(self, other): \"\"\" >>> results = []", "y, y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for", "inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ... ns =", "return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>> results", "bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs", "= output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True \"\"\"", "y])) ... zs = outputs(xs % ys) ... ns =", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ...", "use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return input_one", "for (x, y) in [(0, 0), (0, 1), (1, 0),", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) == input(y)) ...", "x]), inputs([y, y, y])) ... zs = outputs(xs.nimp_(ys)) ... ns", "self.gate = bit._circuit.gate(op.id_, is_input=True) class input_one(input): \"\"\"Bit that is designated", "type(b1) else: return bit \"\"\" return bit @staticmethod def gate(operation,", "for (x, y) in zip(self, other)]) def xnor(self: bits, other:", "[1, 1, 1, 1, 1, 1, 1, 1] >>> bit.circuit(circuit())", "for b in bss[0]], [b.value for b in bss[1]]) ([1,", "integer 1 \"\"\" if other == 1: return bit.operation(op.not_, self)", "@synthesize ... def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0],", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) @ input(y)) ...", "outputs(l): return bits(map(output, l)) def synthesize(f): \"\"\" Decorator for automatically", "1 \"\"\" return self | (constant(other) if isinstance(other, int) else", "(x, y) in zip(self, other)]) def xor(self: bits, other: bits)", "y, y])) ... zs = outputs(xs.xor(ys)) ... ns = [int(z)", "for representing an input or output type of a function", "value self.gate = bit._circuit.gate() if gate_ is None else gate_", "in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy in xys] [[1],", "= output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 = output(b0)", "[b.value for b in bs] [1, 0, 0, 0, 0,", "self, other) def __and__(self, other): \"\"\" >>> results = []", "y, y])) ... zs = outputs(xs.imp_(ys)) ... ns = [int(z)", "bit.operation(op.not_, self) raise ValueError('can only subtract a bit from the", "_ in range(other)]) def __truediv__(self: bits, other) -> Sequence[bits]: \"\"\"", "it to a new wire. self.value = b.value self.gate =", "1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>>", "& constant(1) >>> b.value 0 \"\"\" return self & (constant(other)", "None) -> bits: \"\"\" Return bits object given the supplied", "0, 0, 0]] \"\"\" if isinstance(other, list) and len(other) >", "outputs(xs > ys) ... ns = [int(z) for z in", "= constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys)", "\"\"\" return bit.operation(op.nimp_, self, other) def __gt__(self, other): \"\"\" >>>", "for bs in bss] [[1, 1], [1, 1], [0, 0],", "True \"\"\" return bit.operation(op.nand_, self, other) def nand_(self, other): \"\"\"", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nimp_,", "x])) >>> all(results) True \"\"\" return bits([x.not_() for x in", "for (x, y) in zip(self, other)]) def __le__(self: bits, other:", "def or_(self, other): \"\"\" >>> results = [] >>> for", "objects as its arguments and returns an output of type", "= output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "^ ys) ... ns = [int(z) for z in zs]", "b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) ==", "y, y])) ... zs = outputs(xs & ys) ... ns", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.if_(ys)) ...", "for (x, y) in zip(self, other)]) def xor_(self: bits, other:", "self, other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b", "it to the function as an attribute. bit.circuit(circuit()) args_in =", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) ==", "return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nimp_(self:", "outputs(xs.nimp(ys)) ... ns = [int(z) for z in zs] ...", "representing an input or output type of a function decorated", "return f if __name__ == \"__main__\": doctest.testmod() # pragma: no", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self,", "[int(z) for z in zs] ... c = bit.circuit() ...", "and len(other) > 0 and isinstance(other[0], int): return map(bits, parts(self,", "x]) ... ys = outputs(~xs) ... ns = [int(y) for", ">>> b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2", "if circuit_ is not None: bit._circuit = circuit_ return None", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp(input(y))) ... results.append(int(b)", "all(results) True \"\"\" return bit.operation(op.and_, self, other) def __and__(self, other):", "other)]) def __and__(self: bits, other: bits) -> bits: \"\"\" >>>", "| ((1 - x) & (1 - y)) >>> xys", "bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "that is designated an output. >>> bit.circuit(circuit()) >>> b0 =", "= value self.gate = bit._circuit.gate() if gate_ is None else", "bss = list(bs / 2) >>> ([b.value for b in", "track of relationships between operators and to represent the wires", "(0, 1) for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for", "= output(input(x) < input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "bits([x.xor_(y) for (x, y) in zip(self, other)]) def xor_(self: bits,", "-> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "for (x, y) in zip(self, other)]) def __mod__(self, other) ->", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ... results.append(int(b)", "output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "bits: \"\"\" Return bits object given the supplied argument. \"\"\"", "def __or__(self: bits, other: bits) -> bits: \"\"\" >>> results", "in ys] [1, 1, 1] \"\"\" return bits([constant(0)]*n) def __new__(cls,", "... bit.circuit(circuit()) ... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y)))", "not_(self): \"\"\" >>> results = [] >>> for x in", "return bits([x.not_() for x in self]) def and_(self: bits, other:", "]) @staticmethod def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit())", ">>> all(results) True \"\"\" return bit.operation(op.and_, self, other) def __and__(self,", "def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs", "(k, a) in f.__annotations__.items() if k != 'return' } type_out(eval_(f.__annotations__['return']))(f(**args_in))", "operation(o, *args): # Ensure second argument is a `bit`. args", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.if_, self,", "... zs = outputs(xs.xnor(ys)) ... ns = [int(z) for z", "output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "bit.circuit(circuit()) ... b = output(input(x) | input(y)) ... results.append(int(b) ==", "recent call last): ... RuntimeError: automated circuit synthesis failed \"\"\"", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss =", "bit \"\"\" return bit @staticmethod def gate(operation, igs): return bit._circuit.gate(operation,", "gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None): self.value", "ys] ... c = bit.circuit() ... results.append(ns == c.evaluate([x, x,", "bit.circuit(circuit()) >>> b = output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True", "y, y, y])) >>> all(results) True \"\"\" return bits([x.imp_(y) for", "Construct the circuit and add it to the function as", "-> bits(2): ... return (xy[0], xy[0] & xy[1]) >>> xys", "# For forward-compatibility with PEP 563. eval_ = lambda a:", "other) def nand(self, other): \"\"\" >>> results = [] >>>", "in [0, 1]: ... bit.circuit(circuit()) ... b = output(~input(x)) ...", "y) | ((1 - x) & (1 - y)) >>>", "# Number of parts is `other`. def __add__(self: bits, other)", "not currently in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2,", "bits([x.and_(y) for (x, y) in zip(self, other)]) def __and__(self: bits,", "args])) @staticmethod def constructor(b1, b2=None): # The inference code below", "b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "y, y])) ... zs = outputs(xs | ys) ... ns", "b = output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "parts(self, length=other)) # Sequence of lengths. elif isinstance(other, set) and", ">>> for (x, y) in [(0, 0), (0, 1), (1,", "output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", ">>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit):", "a: input(0) if a is bit else inputs([0] * a)", "x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys)) ... ns", "a constant input.\"\"\" class input(bit): \"\"\"Bit that is designated as", "output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "-> bits: \"\"\" >>> bit.circuit(circuit()) >>> xs = bits.zeros(3) >>>", "y) in zip(self, other)]) def nif(self: bits, other: bits) ->", "and isinstance(list(other)[0], int): # Rotation. quantity = list(other)[0] return bits(self[len(self)-quantity:])", "... b = output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "\"\"\" return bits([x.nand_(y) for (x, y) in zip(self, other)]) def", "bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1], int) else", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bs = bs <<", "xy[0] & xy[1]) >>> xys = [bits([x, y]) for x", "== 2: args[1] = constant(args[1]) if isinstance(args[1], int) else args[1]", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nif_(ys)) ...", "y, y])) ... zs = outputs(xs.nif_(ys)) ... ns = [int(z)", "or `bits`. >>> @synthesize ... def equal(x: bit, y: bit)", "1, 1, 1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>>", "bits([x.imp_(y) for (x, y) in zip(self, other)]) def nand(self: bits,", "1 \"\"\" if other == 1: return bit.operation(op.not_, self) raise", ">>> @synthesize ... def conjunction(xy: bits(2)) -> bits(2): ... return", "def __gt__(self, other): \"\"\" >>> results = [] >>> for", "subtract a bit from the integer 1 \"\"\" if other", "return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>> results", "return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\" >>> results", "shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>>", "else inputs([0] * a) type_out = lambda a: output if", "pylint: disable=W0123 try: # Construct the circuit and add it", "@staticmethod def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value,", "y, y])) ... zs = outputs(xs.nand_(ys)) ... ns = [int(z)", "def inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output, l))", "[y.value for y in ys] [1, 1, 1] \"\"\" return", "= inputs([x, x, x]) ... ys = outputs(~xs) ... ns", "other)]) def __lt__(self: bits, other: bits) -> bits: \"\"\" >>>", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_, self, other)", "# Check if bit is ready as final output or", "bit.operation(op.nor_, self, other) def xnor(self, other): \"\"\" >>> results =", "bs] [1, 0, 0, 0, 0, 0, 0, 0] \"\"\"", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b)", "those definitions. \"\"\" from __future__ import annotations from typing import", "1]: ... bit.circuit(circuit()) ... b = output(1 - input(x)) ...", "return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0)))", "\"\"\" return bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>>", "for byte_ in bytes_ for bit_ in bits.from_byte(byte_, constructor) ])", "1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy) for xy", "bs in bss] [[1, 1], [1, 1], [0, 0], [0,", "= outputs(xs.not_()) ... ns = [int(y) for y in ys]", "a: output if a is bit else outputs # For", "output(input(x) & input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "0, 0, 0, 1] \"\"\" if isinstance(other, set) and isinstance(list(other)[0],", "zip(self, other)]) def xnor_(self: bits, other: bits) -> bits: \"\"\"", "from __future__ import annotations from typing import Sequence import doctest", "self + other def constants(l): return bits(map(constant, l)) def inputs(l):", "other) def __lt__(self, other): \"\"\" >>> results = [] >>>", "bss] [[1, 1], [1, 1], [0, 0], [0, 0]] >>>", "... b = output(input(x) | input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "0]] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss", "1, 0, 0, 0, 0, 1] \"\"\" if isinstance(other, set)", "int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)),", "else a # pylint: disable=W0123 try: # Construct the circuit", "def nimp(self, other): \"\"\" >>> results = [] >>> for", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) & input(y))", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def nif(self, other):", "return bits([constant(0)]*n) def __new__(cls, argument = None) -> bits: \"\"\"", "failed') from None # Return the original function. return f", "it is also used to keep track of relationships between", "& y Traceback (most recent call last): ... RuntimeError: automated", "all(results) True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\"", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... (xs, ys) =", "= outputs(xs.not_()) >>> int(ys) 7 \"\"\" return sum(int(b)*(2**i) for (i,", "x in (0, 1) for y in (0, 1)] >>>", "self.value = b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int):", "doctest from parts import parts from circuit import op, gate,", "bits([x.nor_(y) for (x, y) in zip(self, other)]) def xnor(self: bits,", "self, other) def __le__(self, other): \"\"\" >>> results = []", "y, y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for (x,", "if_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "zs = outputs(xs.nand(ys)) ... ns = [int(z) for z in", "isinstance(b1, input_one) and isinstance(b2, input_one): return input_one elif isinstance(b1, input_two)", "def nand_(self: bits, other) -> bits: \"\"\" >>> results =", "-> bits: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))", "- y)) >>> xys = [bits([x, y]) for x in", "nimp_(self, other): \"\"\" >>> results = [] >>> for (x,", "decorated function. type_in = lambda a: input(0) if a is", "[b.value for b in bs] [1, 1, 1, 0, 0,", "l)) def synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit", "is not None: r = bit._hook_operation(o, v, *args) if r", "inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ... ns =", "a function that takes only `bit` and/or `bits` objects as", "bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>> results =", "bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity]) else: # Shift return bits([constant(0)]*other) ** bits(self[0:len(self)-other])", "\"\"\" def __init__(self: bit, b: bit): # Check if bit", "[b.value for b in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0,", "y) in zip(self, other)]) def nor_(self: bits, other: bits) ->", "1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor(ys))", "True \"\"\" return bit.operation(op.not_, self) def __rsub__(self, other): \"\"\" >>>", "# the type annotation of the decorated function. type_in =", "... b = output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "synthesis failed') from None # Return the original function. return", ">>> bit.circuit(circuit()) >>> [b.value for b in bits.from_bytes(bytes([11, 0]))] [0,", "`other`. else: return map(bits, parts(self, other)) # Number of parts", "x]), inputs([y, y, y])) ... zs = outputs(xs.xnor(ys)) ... ns", "the circuit and add it to the function as an", "... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "= output(input(x) >= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "\"\"\" return bits([x.nif_(y) for (x, y) in zip(self, other)]) def", "1, 0] \"\"\" def __init__(self: bit, b: bit): # Check", "code below is not currently in use. \"\"\" if isinstance(b1,", "in [(0, 0), (0, 1), (1, 0), (1, 1)]: ...", "return bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nif(self:", "and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts of", "b = output(input(0).and_(input(0))) >>> b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit", "\"\"\" Overloaded operator: rotation and shift operations. >>> bit.circuit(circuit()) >>>", "parts from circuit import op, gate, circuit, signature class bit():", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) ==", "b in bs] [0, 0, 0, 1, 1, 1, 1,", "bit.circuit(circuit()) ... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>>", ">>> all(results) True \"\"\" return bit.operation(op.nif_, self, other) def __lt__(self,", "self.value = value self.gate = bit._circuit.gate() if gate_ is None", "in zip(self, other)]) def xor_(self: bits, other: bits) -> bits:", "y])) >>> all(results) True \"\"\" return bits([x.or_(y) for (x, y)", "1], [1, 1], [0, 0], [0, 0]] >>> bit.circuit(circuit()) >>>", "zip(self, other)]) def xnor(self: bits, other: bits) -> bits: \"\"\"", "in [0, 1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ...", "final output or whether there are others dependent on it.", ">>> bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>> b.value", "\"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def", "def imp(self: bits, other: bits) -> bits: \"\"\" >>> results", "a vector of abstract bits. \"\"\" @staticmethod def from_byte(byte_: int,", "other) def nimp(self, other): \"\"\" >>> results = [] >>>", "b = output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) -> bits:", "(x, y) in zip(self, other)]) def nand(self: bits, other) ->", "... bit.circuit(circuit()) ... b = output(input(x).and_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "is bit else inputs([0] * a) type_out = lambda a:", "return bits([x.or_(y) for (x, y) in zip(self, other)]) def nor(self:", "bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def __truediv__(self: bits,", "1 ^ constant(0) >>> b.value 1 \"\"\" return self ^", "... xs = inputs([x, x, x]) ... ys = outputs(xs.not_())", "zs = outputs(xs.or_(ys)) ... ns = [int(z) for z in", "x]), inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ... ns", "... zs = outputs(xs.nimp(ys)) ... ns = [int(z) for z", "nor(self: bits, other: bits) -> bits: \"\"\" >>> results =", "outputs(xs.nor(ys)) ... ns = [int(z) for z in zs] ...", "value of the result of the operation on the arguments.", "xor_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "inputs([y, y, y])) ... zs = outputs(xs.xor_(ys)) ... ns =", "0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs", "bits: \"\"\" >>> results = [] >>> for (x, y)", "a `bit`. args = list(args) if len(args) == 2: args[1]", "other)]) def nand_(self: bits, other) -> bits: \"\"\" >>> results", "True \"\"\" return bit.operation(op.xnor_, self, other) def if_(self, other): \"\"\"", "= bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / {2}) >>>", "def __invert__(self): \"\"\" >>> results = [] >>> for x", "parts import parts from circuit import op, gate, circuit, signature", "argument = None) -> bits: \"\"\" Return bits object given", "bit._hook_operation = hook @staticmethod def operation(o, *args): # Ensure second", "self, other) def nif_(self, other): \"\"\" >>> results = []", "nif_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "Parts of length `other`. else: return map(bits, parts(self, other)) #", "b.value == bit.circuit().evaluate([0,0])[0] True \"\"\" _circuit = None _hook_operation =", "constructor=bit) -> bits: return bits([ constructor(bit_) for bit_ in reversed([(byte_>>i)%2", "nif(self: bits, other: bits) -> bits: \"\"\" >>> results =", "for (x, y) in zip(self, other)]) def __ge__(self: bits, other:", "0, 0, 0, 0, 0] \"\"\" return bits([ bit_ for", "type_out(eval_(f.__annotations__['return']))(f(**args_in)) f.circuit = bit.circuit() except: raise RuntimeError('automated circuit synthesis failed')", "& y) | ((1 - x) & (1 - y))", "0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\" return", "for (x, y) in zip(self, other)]) def nand_(self: bits, other)", "the original function. return f if __name__ == \"__main__\": doctest.testmod()", "ys = outputs(xs.not_()) ... ns = [int(y) for y in", "... b = output(~input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results)", "0, 0, 0, 0] \"\"\" return bits([ bit_ for byte_", "in bss] [[1], [1, 1, 1], [0, 0, 0, 0]]", "circuit synthesis failed') from None # Return the original function.", "other): \"\"\" >>> results = [] >>> for x in", "7 \"\"\" return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self)))", "... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))", "zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits: \"\"\" >>> results", "in zip(self, other)]) def nor(self: bits, other: bits) -> bits:", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor(input(y)))", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) == input(y))", "(x, y) in zip(self, other)]) def imp_(self: bits, other: bits)", "bit.circuit(circuit()) ... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "other): \"\"\" >>> bit.circuit(circuit()) >>> b = 0 & constant(1)", "in use. \"\"\" if isinstance(b1, input_one) and isinstance(b2, input_one): return", ">>> [b0.value, b1.value, b2.value] [0, 1, 0] \"\"\" def __init__(self:", "= output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "bit._hook_operation(o, v, *args) if r is not None: return r", "for (x, y) in zip(self, other)]) def nimp(self: bits, other:", "arguments. v = o(*[a.value for a in args]) # Return", "if isinstance(other, int) else other) def nor(self, other): \"\"\" >>>", "1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>> bs =", "zip(self, other)]) def xor_(self: bits, other: bits) -> bits: \"\"\"", "automated circuit synthesis failed \"\"\" # Functions for determining types/signature", ">= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "== bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ... def hook(o, v,", "(inputs([x, x, x]), inputs([y, y, y])) ... zs = outputs(xs.nand_(ys))", "def __gt__(self: bits, other: bits) -> bits: \"\"\" >>> results", "... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "bit_ in reversed([(byte_>>i)%2 for i in range(8)]) ]) @staticmethod def", ">>> for x in [0, 1]: ... bit.circuit(circuit()) ... xs", "bit.circuit(circuit()) ... b = output(input(x).xnor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "= outputs(xs.xnor_(ys)) ... ns = [int(z) for z in zs]", "the supplied argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\", "bit, value: int): self.value = value self.gate = bit._circuit.gate(op.id_, is_input=True)", "y) in zip(self, other)]) def or_(self: bits, other: bits) ->", "outputs(xs <= ys) ... ns = [int(z) for z in", "from the integer 1 \"\"\" if other == 1: return", "0, 0] \"\"\" return bits([ bit_ for byte_ in bytes_", "else: return bit \"\"\" return bit @staticmethod def gate(operation, igs):", "r is not None: return r return bit.constructor(*args)(v, bit.gate(o, [a.gate", "zip(self, other)]) def nand(self: bits, other) -> bits: \"\"\" >>>", "return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\" >>> results", "zs = outputs(xs.xor_(ys)) ... ns = [int(z) for z in", "in zip(self, other)]) def __rshift__(self: bits, other) -> bits: \"\"\"", "nand_(self, other): \"\"\" >>> results = [] >>> for (x,", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand(input(y))) ...", "bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>> b.value 1", "(x, y) in zip(self, other)]) def __ge__(self: bits, other: bits)", "designated an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_()) >>>", "def __rsub__(self, other): \"\"\" >>> results = [] >>> for", "bit.gate(o, [a.gate for a in args])) @staticmethod def constructor(b1, b2=None):", "x]), inputs([y, y, y])) ... zs = outputs(xs.nimp(ys)) ... ns", "... zs = outputs(xs % ys) ... ns = [int(z)", "= output(input(x) % input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "int) else other) def nimp(self, other): \"\"\" >>> results =", "... bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "other): \"\"\" >>> results = [] >>> for (x, y)", "xs = constants([0, 0, 0]) >>> ys = outputs(xs.not_()) >>>", "a is bit else inputs([0] * a) type_out = lambda", "0, 0]) >>> ys = outputs(xs.not_()) >>> int(ys) 7 \"\"\"", "bit.operation(op.imp_, self, other) def __le__(self, other): \"\"\" >>> results =", "bit.operation(op.xor_, self, other) def xor_(self, other): \"\"\" >>> results =", "(i, b) in zip(range(len(self)), reversed(self))) def not_(self: bits) -> bits:", "= outputs(xs.xnor(ys)) ... ns = [int(z) for z in zs]", "... bit.circuit(circuit()) ... (xs, ys) = (inputs([x, x, x]), inputs([y,", "Traceback (most recent call last): ... ValueError: can only subtract", "/ [1, 3, 4]) >>> [[b.value for b in bs]", "= bit.circuit() except: raise RuntimeError('automated circuit synthesis failed') from None", "value, gate_=None): self.value = value self.gate = bit._circuit.gate() if gate_", "other): \"\"\" >>> bit.circuit(circuit()) >>> b = 1 | constant(0)", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif(input(y))) ... results.append(int(b) ==", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nif_,", ">>> xys = [bits([x, y]) for x in (0, 1)", "(x, y) in zip(self, other)]) def nand_(self: bits, other) ->", "c.evaluate([x, x, x])) >>> all(results) True \"\"\" return bits([x.not_() for", "in (0, 1) for y in (0, 1)] >>> [equal.circuit.evaluate(xy)", "0, 0, 0, 0, 0, 0] \"\"\" return bits([ bit_", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.nor_(ys)) ...", "up out of those operators. >>> bit.hook_operation(lambda o, v, *args:", "input.\"\"\" def __init__(self: bit, value: int): self.value = value self.gate", "input or output type of a function decorated for automated", "y])) ... zs = outputs(xs.xor_(ys)) ... ns = [int(z) for", "... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "1]: ... bit.circuit(circuit()) ... b = output(input(x).not_()) ... results.append(int(b) ==", "else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook", "argument is a `bit`. args = list(args) if len(args) ==", "... b = output(input(x).not_()) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results)", "in bss[1]]) ([1, 1, 1, 1], [0, 0, 0, 0])", "b = output(input(x).xor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "in zip(self, other)]) def nor_(self: bits, other: bits) -> bits:", "other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b =", "= output(input(x).imp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "563. eval_ = lambda a: eval(a) if isinstance(a, str) else", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).or_(input(y))) ...", ">>> all(results) True \"\"\" return bit.operation(op.nor_, self, other) def __mod__(self,", "@staticmethod def zeros(n: int) -> bits: \"\"\" >>> bit.circuit(circuit()) >>>", "outputs(xs.xnor(ys)) ... ns = [int(z) for z in zs] ...", "... bit.circuit(circuit()) ... b = output(input(x) % input(y)) ... results.append(int(b)", ">>> bss = list(bs / [1, 3, 4]) >>> [[b.value", "in xys] [[0, 0], [0, 0], [1, 0], [1, 1]]", "bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other) class", "__truediv__(self: bits, other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs", "[1,1,1,1,0,0,0,0])) >>> bs = bs << 3 >>> [b.value for", "True \"\"\" return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that", "inputs([y, y, y])) ... zs = outputs(xs.imp(ys)) ... ns =", "# pylint: disable=W0123 try: # Construct the circuit and add", "bit.circuit(circuit()) ... b = output(input(x).xor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x) <", "1)]: ... bit.circuit(circuit()) ... b = output(input(x) < input(y)) ...", "list(args) if len(args) == 2: args[1] = constant(args[1]) if isinstance(args[1],", "a is bit else outputs # For forward-compatibility with PEP", "\"\"\"Bit that is designated as a variable input from a", "-> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self + other", "synthesizing a circuit from a function that takes only `bit`", "None: bit._circuit = circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit", "-> bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other))", "def __init__(self: bit, value: int): self.value = value self.gate =", "is_output=True) class bits_type(int): # pylint: disable=R0903 \"\"\" Class for representing", "1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for b", "** bits(self[0:len(self)-other]) def __lshift__(self: bits, other) -> bits: \"\"\" >>>", "output from hook if it exists and if # it", "None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation =", "def __xor__(self: bits, other: bits) -> bits: \"\"\" >>> results", "None: r = bit._hook_operation(o, v, *args) if r is not", "xnor_(self: bits, other: bits) -> bits: \"\"\" >>> results =", "bit) -> bit: ... return (x & y) | ((1", "other) def __ror__(self, other): \"\"\" >>> bit.circuit(circuit()) >>> b =", "def synthesize(f): \"\"\" Decorator for automatically synthesizing a circuit from", "... zs = outputs(xs.or_(ys)) ... ns = [int(z) for z", "in bits.from_bytes(bytes([11, 0]))] [0, 0, 0, 0, 1, 0, 1,", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xnor(input(y)))", "(x, y) in zip(self, other)]) def nif(self: bits, other: bits)", "(x, y) in zip(self, other)]) def __le__(self: bits, other: bits)", "of the decorated function. type_in = lambda a: input(0) if", "in zip(self, other)]) def __mod__(self, other) -> bits: \"\"\" >>>", "it exists and if # it returns an output. if", "else outputs # For forward-compatibility with PEP 563. eval_ =", "an attribute. bit.circuit(circuit()) args_in = { k: type_in(eval_(a)) for (k,", "== 1 and isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) #", "... b = output(input(x) == input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "True \"\"\" return bit.operation(op.xnor_, self, other) def xnor_(self, other): \"\"\"", "\"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss", "(x, y) in zip(self, other)]) def xnor_(self: bits, other: bits)", "circuit from a function that takes only `bit` and/or `bits`", "y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:", "isinstance(list(other)[0], int): return self / (len(self)//list(other)[0]) # Parts of length", "return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self))) def not_(self:", "self.gate = bit._circuit.gate() if gate_ is None else gate_ def", "in bs] [1, 1, 1, 0, 0, 0, 0, 1]", "\"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\" >>>", "of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return bits(result) def", "inputs([y, y, y])) ... zs = outputs(xs.nand_(ys)) ... ns =", "\"\"\" return bits(self[other:]) ** bits([constant(0) for _ in range(other)]) def", "def xnor(self, other): \"\"\" >>> results = [] >>> for", "output(input(x).nif(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "def from_byte(byte_: int, constructor=bit) -> bits: return bits([ constructor(bit_) for", "0], [0, 0], [1, 0], [1, 1]] >>> @synthesize ...", "return bit.operation(op.nand_, self, other) class constant(bit): \"\"\"Bit that is designated", "= o(*[a.value for a in args]) # Return output from", "y in ys] ... c = bit.circuit() ... results.append(ns ==", "outputs(xs.xnor_(ys)) ... ns = [int(z) for z in zs] ...", "x, x]), inputs([y, y, y])) ... zs = outputs(xs <", "x, x]), inputs([y, y, y])) ... zs = outputs(xs ==", "def nor_(self: bits, other: bits) -> bits: \"\"\" >>> results", "zip(self, other)]) def imp_(self: bits, other: bits) -> bits: \"\"\"", "\"\"\" return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results =", "that takes only `bit` and/or `bits` objects as its arguments", "y, y])) ... zs = outputs(xs.nor_(ys)) ... ns = [int(z)", "other) def xor_(self, other): \"\"\" >>> results = [] >>>", "o, v, *args: None) >>> bit.circuit(circuit()) >>> b = output(input(1).and_(input(1)))", "outputs(xs ^ ys) ... ns = [int(z) for z in", "if isinstance(args[1], int) else args[1] # Compute the value of", "other)]) def xor_(self: bits, other: bits) -> bits: \"\"\" >>>", "x]), inputs([y, y, y])) ... zs = outputs(xs.nif(ys)) ... ns", "b in bs] [1, 1, 1, 0, 0, 0, 0,", "0, 0, 1, 1, 1, 1, 0] >>> bit.circuit(circuit()) >>>", "all(results) True \"\"\" return bit.operation(op.xnor_, self, other) def __eq__(self, other):", "... def equal(x: bit, y: bit) -> bit: ... return", "bit.circuit(circuit()) ... b = output(input(x).nimp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bit.circuit(circuit()) ... b = output(input(x).nor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "bits([x.xnor_(y) for (x, y) in zip(self, other)]) def xnor_(self: bits,", "x, x]) ... ys = outputs(xs.not_()) ... ns = [int(y)", "abstract bit. Such a bit can be interpreted concretely as", "out of those operators. >>> bit.hook_operation(lambda o, v, *args: None)", "for (x, y) in zip(self, other)]) def nif(self: bits, other:", "= circuit_ return None else: bit._circuit.prune_and_topological_sort_stable() return bit._circuit @staticmethod def", ">>> bss = list(bs / {2}) >>> [[b.value for b", "x, y, y, y])) >>> all(results) True \"\"\" return bits([x.nimp_(y)", "b.value self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True) class bits_type(int): # pylint:", "bits([x.nimp_(y) for (x, y) in zip(self, other)]) def nif(self: bits,", "output(input(1).and_(input(1))) >>> b.value == bit.circuit().evaluate([1,1])[0] True >>> def make_hook(bit_): ...", "within a circuit built up out of those operators. >>>", "[[1], [0], [0], [1]] >>> @synthesize ... def conjunction(xy: bits(2))", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_,", ">>> bit.circuit(circuit()) >>> b = 0 & constant(1) >>> b.value", "source.\"\"\" class output(bit): \"\"\" Bit that is designated an output.", "True \"\"\" return bit.operation(op.imp_, self, other) def nand(self, other): \"\"\"", "... zs = outputs(xs.nand(ys)) ... ns = [int(z) for z", "pylint: disable=R0903 \"\"\" Class for representing an input or output", "return bits([x.nand_(y) for (x, y) in zip(self, other)]) def __rshift__(self:", "= lambda a: output if a is bit else outputs", "__xor__(self, other): \"\"\" >>> results = [] >>> for (x,", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.and_, self, other)", "y])) ... zs = outputs(xs | ys) ... ns =", "output(input(x).nimp(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).imp_(input(y)))", "for b in bs] [0, 0, 0, 1, 1, 1,", "def gate(operation, igs): return bit._circuit.gate(operation, igs) def __init__(self, value, gate_=None):", "constant(bit): \"\"\"Bit that is designated as a constant input.\"\"\" class", "result.extend(list(other)) return bits(result) def __pow__(self: bits, other) -> bits: \"\"\"Concatenation", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).xor_(input(y))) ...", "# pylint: disable=R0903 \"\"\" Class for representing an input or", "outputs(xs.nif(ys)) ... ns = [int(z) for z in zs] ...", "(x, y) in zip(self, other)]) def or_(self: bits, other: bits)", "input_two) and isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two))", "(1 - y)) >>> xys = [bits([x, y]) for x", "b2 is None: return type(b1) else: return bit \"\"\" return", "a in args])) @staticmethod def constructor(b1, b2=None): # The inference", "if isinstance(argument, int) else\\ list.__new__(cls, argument) def __int__(self: bits) ->", "x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ... ns", "or output type of a function decorated for automated synthesis.", "b = output(input(x).nif_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "elif isinstance(b1, (input_one, input_two)) and b2 is None: return type(b1)", "1, 1, 0] >>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1]))", "argument. \"\"\" return bits_type(argument)\\ if isinstance(argument, int) else\\ list.__new__(cls, argument)", "outputs(xs.not_()) >>> [y.value for y in ys] [1, 1, 1]", "b0 = output(input(1).not_()) >>> b1 = output(b0.not_()) >>> b2 =", "y) in zip(self, other)]) def imp_(self: bits, other: bits) ->", "bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs / 2) >>> ([b.value", "y, y])) >>> all(results) True \"\"\" return bits([x.nor_(y) for (x,", "bit.operation(op.xnor_, self, other) def __eq__(self, other): \"\"\" >>> results =", "\"\"\" return bit.operation(op.and_, self, other) def __rand__(self, other): \"\"\" >>>", "~(~b) # Preserve the bit by copying it to a", "for y in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in", "f if __name__ == \"__main__\": doctest.testmod() # pragma: no cover", "def __init__(self: bit, b: bit): # Check if bit is", ">>> bs = bits(map(bit, [1,1,1,1,0,0,0,0])) >>> bss = list(bs /", "[] >>> for (x, y) in [(0, 0), (0, 1),", "inputs([x, x, x]) ... ys = outputs(~xs) ... ns =", "<< 3 >>> [b.value for b in bs] [1, 0,", "def nimp_(self: bits, other: bits) -> bits: \"\"\" >>> results", "other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" return self +", "bit_ in bits.from_byte(byte_, constructor) ]) @staticmethod def zeros(n: int) ->", "... zs = outputs(xs.imp(ys)) ... ns = [int(z) for z", ">>> all(results) True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self,", "l)) def inputs(l): return bits(map(input, l)) def outputs(l): return bits(map(output,", "y: bit) -> bit: ... return (x & y) |", "1], [0, 0, 0, 0]) >>> bit.circuit(circuit()) >>> bs =", "and add it to the function as an attribute. bit.circuit(circuit())", "all(results) True \"\"\" return bit.operation(op.or_, self, other) def __or__(self, other):", "x, x]), inputs([y, y, y])) ... zs = outputs(xs ^", "True \"\"\" return bit.operation(op.xor_, self, other) def __xor__(self, other): \"\"\"", "bit.operation(op.xor_, self, other) def __rxor__(self, other): \"\"\" >>> bit.circuit(circuit()) >>>", "a in args])) ... return hook >>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit())", "outputs(xs.nand(ys)) ... ns = [int(z) for z in zs] ...", "for determining types/signature from # the type annotation of the", ">>> def make_hook(bit_): ... def hook(o, v, *args): ... return", "outputs(xs & ys) ... ns = [int(z) for z in", "it. if len(b.gate.outputs) > 0: b = ~(~b) # Preserve", "... b = output(input(x).nand_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "def or_(self: bits, other: bits) -> bits: \"\"\" >>> results", "= outputs(xs.nand_(ys)) ... ns = [int(z) for z in zs]", ">>> ys = outputs(xs.not_()) >>> [y.value for y in ys]", "[1, 0, 0, 0, 0, 0, 0, 0] \"\"\" return", "for b in bs] for bs in bss] [[1], [1,", "x]), inputs([y, y, y])) ... zs = outputs(xs & ys)", "(x, y) in zip(self, other)]) def __and__(self: bits, other: bits)", "(1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ... results.append(int(b)", "in zip(self, other)]) def nimp(self: bits, other: bits) -> bits:", "interpreted concretely as a value, but it is also used", "0, 0, 0, 0, 0, 0] \"\"\" return bits(self[other:]) **", "... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xor_,", "... bit.circuit(circuit()) ... b = output(input(x) < input(y)) ... results.append(int(b)", "(x & y) | ((1 - x) & (1 -", "logic circuits. Embedded domain-specific combinator library for assembling abstract definitions", "def __and__(self, other): \"\"\" >>> results = [] >>> for", "an output of type `bit` or `bits`. >>> @synthesize ...", "... zs = outputs(xs ^ ys) ... ns = [int(z)", "`bits`. >>> @synthesize ... def equal(x: bit, y: bit) ->", "the integer 1 \"\"\" if other == 1: return bit.operation(op.not_,", "nor_(self, other): \"\"\" >>> results = [] >>> for (x,", "parts is `other`. def __add__(self: bits, other) -> bits: \"\"\"Concatenation", "... bit.circuit(circuit()) ... b = output(input(x).if_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0])", "x, x]), inputs([y, y, y])) ... zs = outputs(xs >", "all(results) True \"\"\" return bit.operation(op.nand_, self, other) def __matmul__(self, other):", "isinstance(b2, input_two): return input_two elif isinstance(b1, (input_one, input_two)) and b2", "gate_ def __int__(self): return self.value def not_(self): \"\"\" >>> results", "constant(0) >>> b.value 1 \"\"\" return self ^ (constant(other) if", "bits([x.or_(y) for (x, y) in zip(self, other)]) def nor(self: bits,", "is designated an output. >>> bit.circuit(circuit()) >>> b0 = output(input(1).not_())", "from_bytes(bytes_, constructor=bit) -> bits: \"\"\" >>> bit.circuit(circuit()) >>> [b.value for", "are others dependent on it. if len(b.gate.outputs) > 0: b", "bit.circuit(circuit()) >>> xs = bits.zeros(3) >>> ys = outputs(xs.not_()) >>>", "bit, b: bit): # Check if bit is ready as", "input(0) Traceback (most recent call last): ... ValueError: can only", "True \"\"\" return bits([x.not_() for x in self]) def __invert__(self:", "xy in xys] [[0, 0], [0, 0], [1, 0], [1,", "(1, 0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nor_(input(y)))", "other)]) def xnor(self: bits, other: bits) -> bits: \"\"\" >>>", "output(input(x).xnor(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.xnor_, self, other)", "def equal(x, y): ... return x & y Traceback (most", "Traceback (most recent call last): ... RuntimeError: automated circuit synthesis", "... zs = outputs(xs <= ys) ... ns = [int(z)", "self.value def not_(self): \"\"\" >>> results = [] >>> for", "gate_ is None else gate_ def __int__(self): return self.value def", "isinstance(args[1], int) else args[1] # Compute the value of the", "def nand(self: bits, other) -> bits: \"\"\" >>> results =", "class input_one(input): \"\"\"Bit that is designated as a variable input", "return bits([x.nif_(y) for (x, y) in zip(self, other)]) def __lt__(self:", "a: eval(a) if isinstance(a, str) else a # pylint: disable=W0123", "-> bits: \"\"\" >>> results = [] >>> for (x,", "b = 1 | constant(0) >>> b.value 1 \"\"\" return", "b: bit): # Check if bit is ready as final", "bit can be interpreted concretely as a value, but it", "length=other)) # Sequence of lengths. elif isinstance(other, set) and len(other)", "if a is bit else outputs # For forward-compatibility with", "imp(self, other): \"\"\" >>> results = [] >>> for (x,", "\"\"\" >>> bit.circuit(circuit()) >>> b = 1 ^ constant(0) >>>", "__int__(self: bits) -> int: \"\"\" >>> bit.circuit(circuit()) >>> xs =", "return bit \"\"\" return bit @staticmethod def gate(operation, igs): return", "@ input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "True \"\"\" return bit.operation(op.nimp_, self, other) def nimp_(self, other): \"\"\"", "y, y])) >>> all(results) True \"\"\" return bits([x.xnor_(y) for (x,", "rotation and shift operations. >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "1)]: ... bit.circuit(circuit()) ... b = output(input(x).nand_(input(y))) ... results.append(int(b) ==", "all(results) True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self, other):", "(x, y) in zip(self, other)]) def __gt__(self: bits, other: bits)", "y) in zip(self, other)]) def __xor__(self: bits, other: bits) ->", "self / (len(self)//list(other)[0]) # Parts of length `other`. else: return", "__gt__(self, other): \"\"\" >>> results = [] >>> for (x,", ">>> all(results) True \"\"\" return bit.operation(op.or_, self, other) def __ror__(self,", "input(x)) ... results.append(int(b) == bit.circuit().evaluate([x])[0]) >>> all(results) True >>> bit.circuit(circuit())", "outputs(xs | ys) ... ns = [int(z) for z in", "input_two)) and b2 is None: return type(b1) else: return bit", "x, x]), inputs([y, y, y])) ... zs = outputs(xs.and_(ys)) ...", "return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args])) ... return", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.imp_, self, other)", "output(input(x).nand(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "__int__(self): return self.value def not_(self): \"\"\" >>> results = []", "for b in bits.from_bytes(bytes([255]))] [1, 1, 1, 1, 1, 1,", "def xnor(self: bits, other: bits) -> bits: \"\"\" >>> results", "disable=R0903 \"\"\" Class for representing an input or output type", "other) -> Sequence[bits]: \"\"\" >>> bit.circuit(circuit()) >>> bs = bits(map(bit,", "1, 1, 1, 1, 1] >>> bit.circuit(circuit()) >>> [b.value for", "y, y])) >>> all(results) True \"\"\" return bits([x.nand_(y) for (x,", "in args]) # Return output from hook if it exists", "def conjunction(xy: bits(2)) -> bits(2): ... return (xy[0], xy[0] &", "y])) >>> all(results) True \"\"\" return bits([x.xor_(y) for (x, y)", "variable input.\"\"\" def __init__(self: bit, value: int): self.value = value", "... zs = outputs(xs.nif_(ys)) ... ns = [int(z) for z", "y])) ... zs = outputs(xs == ys) ... ns =", "as its arguments and returns an output of type `bit`", "b = output(input(x) <= input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>>", "__add__(self: bits, other) -> bits: \"\"\"Concatenation of bit vectors.\"\"\" result", "return bit._circuit @staticmethod def hook_operation(hook=None): bit._hook_operation = hook @staticmethod def", "y) in zip(self, other)]) def nand(self: bits, other) -> bits:", "zs = outputs(xs.xnor(ys)) ... ns = [int(z) for z in", "... b = output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results)", "- input(0) Traceback (most recent call last): ... ValueError: can", "y])) ... zs = outputs(xs >= ys) ... ns =", "(most recent call last): ... RuntimeError: automated circuit synthesis failed", "to a new wire. self.value = b.value self.gate = bit._circuit.gate(op.id_,", "= list(bs / [1, 3, 4]) >>> [[b.value for b", "(0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0, 0],", "other) def __or__(self, other): \"\"\" >>> results = [] >>>", "class bits(list): \"\"\" Class for representing a vector of abstract", "bits([x.nor_(y) for (x, y) in zip(self, other)]) def __mod__(self, other)", "is bit else outputs # For forward-compatibility with PEP 563.", "bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs = bs >> {3}", "that is designated as a variable input.\"\"\" def __init__(self: bit,", "__gt__(self: bits, other: bits) -> bits: \"\"\" >>> results =", "a second source.\"\"\" class output(bit): \"\"\" Bit that is designated", "== bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return bit.operation(op.nand_, self, other)", "bits: \"\"\"Concatenation of bit vectors.\"\"\" result = list(self) result.extend(list(other)) return", ">>> b1 = output(b0.not_()) >>> b2 = output(b0) >>> [b0.value,", "__invert__(self: bits) -> bits: \"\"\" >>> results = [] >>>", "a bit from the integer 1 \"\"\" if other ==", "| (constant(other) if isinstance(other, int) else other) def nor(self, other):", "`bits` objects as its arguments and returns an output of", "if isinstance(other, int) else other) def nimp(self, other): \"\"\" >>>", "class bit(): \"\"\" Class for representing an abstract bit. Such", "= outputs(xs.not_()) >>> [y.value for y in ys] [1, 1,", "the wires within a circuit built up out of those", "y])) ... zs = outputs(xs < ys) ... ns =", "parts(self, other)) # Number of parts is `other`. def __add__(self:", "for (x, y) in zip(self, other)]) def xnor_(self: bits, other:", "synthesis failed \"\"\" # Functions for determining types/signature from #", ">>> bit.circuit(circuit()) >>> bs = bits(map(bit, [0,0,0,0,1,1,1,1])) >>> bs =", "0), (1, 1)]: ... bit.circuit(circuit()) ... b = output(input(x).nif_(input(y))) ...", ">>> all(results) True \"\"\" return bits([x.nif_(y) for (x, y) in", "0, 0, 0, 0, 0, 0, 0, 0] \"\"\" return", "x]), inputs([y, y, y])) ... zs = outputs(xs == ys)", "x, x])) >>> all(results) True \"\"\" return bits([x.not_() for x", "< input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "y, y])) ... zs = outputs(xs.xnor(ys)) ... ns = [int(z)", "__lt__(self, other): \"\"\" >>> results = [] >>> for (x,", "in zip(self, other)]) def imp_(self: bits, other: bits) -> bits:", "zs = outputs(xs.imp_(ys)) ... ns = [int(z) for z in", "\"\"\" return bits([x.and_(y) for (x, y) in zip(self, other)]) def", "[0, 1, 0] \"\"\" def __init__(self: bit, b: bit): #", "/ (len(self)//list(other)[0]) # Parts of length `other`. else: return map(bits,", "... bit.circuit(circuit()) ... b = output(1 - input(x)) ... results.append(int(b)", "in (0, 1)] >>> [conjunction.circuit.evaluate(xy) for xy in xys] [[0,", "return bit.operation(op.not_, self) def __invert__(self): \"\"\" >>> results = []", "= lambda a: input(0) if a is bit else inputs([0]", "a circuit from a function that takes only `bit` and/or", "y) in zip(self, other)]) def xnor_(self: bits, other: bits) ->", "= None @staticmethod def circuit(circuit_=None): if circuit_ is not None:", "b = output(input(x).nor_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True", "bits([x.imp_(y) for (x, y) in zip(self, other)]) def __le__(self: bits,", "the arguments. v = o(*[a.value for a in args]) #", "def __eq__(self: bits, other: bits) -> bits: \"\"\" >>> results", "= output(input(x).imp_(input(y))) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\"", "other) def __matmul__(self, other): \"\"\" >>> results = [] >>>", "bit from the integer 1') def and_(self, other): \"\"\" >>>", "results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return self.nimp(other) def", "\"\"\" Class for representing a vector of abstract bits. \"\"\"", "for (x, y) in zip(self, other)]) def if_(self: bits, other:", "to keep track of relationships between operators and to represent", "zs = outputs(xs.xor(ys)) ... ns = [int(z) for z in", "other)]) def __xor__(self: bits, other: bits) -> bits: \"\"\" >>>", "input(y)) ... results.append(int(b) == bit.circuit().evaluate([x,y])[0]) >>> all(results) True \"\"\" return", "and to represent the wires within a circuit built up", "all(results) True \"\"\" return bits([x.imp_(y) for (x, y) in zip(self,", "y Traceback (most recent call last): ... RuntimeError: automated circuit", ">>> bit.hook_operation(make_hook(bit)) >>> bit.circuit(circuit()) >>> b = output(input(0).and_(input(0))) >>> b.value", "y, y])) ... zs = outputs(xs.xor_(ys)) ... ns = [int(z)", "\"\"\" return bit.operation(op.nif_, self, other) def __lt__(self, other): \"\"\" >>>", "bit.operation(op.nand_, self, other) def __matmul__(self, other): \"\"\" >>> results =", ">>> all(results) True \"\"\" return bits([x.nor_(y) for (x, y) in", "1') def and_(self, other): \"\"\" >>> results = [] >>>", "x]), inputs([y, y, y])) ... zs = outputs(xs.nand(ys)) ... ns" ]
[ "plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png')", "= {} for i in author: if i in message_counter:", "# for not mentioning the bot in the line graph.", "= df['author'].to_list() message_counter = {} for i in author: if", "list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10)", "plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by author", "matplotlib.pyplot as plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight')", "in message_counter: message_counter[i] += 1 else: message_counter[i] = 1 #", "pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {} for", "for i in author: if i in message_counter: message_counter[i] +=", "i in message_counter: message_counter[i] += 1 else: message_counter[i] = 1", "list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by", "= 1 # for not mentioning the bot in the", "graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages,", "the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await ctx.send(file =", "import datetime import pandas as pd import matplotlib.pyplot as plt", "author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await", "as plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df", "in author: if i in message_counter: message_counter[i] += 1 else:", "= list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o',", "no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg", "import matplotlib.pyplot as plt import csv async def plot_user_activity(client, ctx):", "+= 1 else: message_counter[i] = 1 # for not mentioning", "in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages =", "by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close()", "the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys())", "message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker", "'o', markersize=10) plt.title('msg sent by author in the server.') plt.xlabel('Author')", "random from datetime import datetime import pandas as pd import", "datetime import pandas as pd import matplotlib.pyplot as plt import", "def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author", "df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter =", "message_counter[i] += 1 else: message_counter[i] = 1 # for not", "markersize=10) plt.title('msg sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count')", "csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding=", "in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await ctx.send(file", "the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values())", "message_counter[i] = 1 # for not mentioning the bot in", "= list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker = 'o', markersize=10) plt.title('msg sent", "import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv',", "mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord =", "async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape')", "pd import matplotlib.pyplot as plt import csv async def plot_user_activity(client,", "as pd import matplotlib.pyplot as plt import csv async def", "bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages", "i in author: if i in message_counter: message_counter[i] += 1", "import random from datetime import datetime import pandas as pd", "message_counter = {} for i in author: if i in", "for not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test')", "{} for i in author: if i in message_counter: message_counter[i]", "pandas as pd import matplotlib.pyplot as plt import csv async", "1 else: message_counter[i] = 1 # for not mentioning the", "author: if i in message_counter: message_counter[i] += 1 else: message_counter[i]", "plt import csv async def plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df =", "author = df['author'].to_list() message_counter = {} for i in author:", "'unicode_escape') author = df['author'].to_list() message_counter = {} for i in", "not mentioning the bot in the line graph. message_counter.pop('ninza_bot_test') authors_in_discord", "discord import random from datetime import datetime import pandas as", "import pandas as pd import matplotlib.pyplot as plt import csv", "1 # for not mentioning the bot in the line", "authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord, no_of_messages, marker =", "plot_user_activity(client, ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author =", "ctx): plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list()", "marker = 'o', markersize=10) plt.title('msg sent by author in the", "datetime import datetime import pandas as pd import matplotlib.pyplot as", "= pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {}", "plt.style.use('fivethirtyeight') df = pd.read_csv('innovators.csv', encoding= 'unicode_escape') author = df['author'].to_list() message_counter", "encoding= 'unicode_escape') author = df['author'].to_list() message_counter = {} for i", "sent by author in the server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout()", "else: message_counter[i] = 1 # for not mentioning the bot", "message_counter: message_counter[i] += 1 else: message_counter[i] = 1 # for", "from datetime import datetime import pandas as pd import matplotlib.pyplot", "= 'o', markersize=10) plt.title('msg sent by author in the server.')", "df['author'].to_list() message_counter = {} for i in author: if i", "server.') plt.xlabel('Author') plt.ylabel('Message_count') plt.savefig('output2.png') plt.tight_layout() plt.close() await ctx.send(file = discord.File('output2.png'))", "if i in message_counter: message_counter[i] += 1 else: message_counter[i] =", "import discord import random from datetime import datetime import pandas", "no_of_messages, marker = 'o', markersize=10) plt.title('msg sent by author in", "line graph. message_counter.pop('ninza_bot_test') authors_in_discord = list(message_counter.keys()) no_of_messages = list(message_counter.values()) plt.plot(authors_in_discord," ]
[ "open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation", "of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\",", "long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\",", "fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of", "import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__),", "return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast", "[\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering :: Artificial Intelligence\"], )", "install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]},", "python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering :: Artificial", "python3 import os from setuptools import setup def read(fname): return", "<reponame>skojaku/fastnode2vec<gh_stars>10-100 #!/usr/bin/env python3 import os from setuptools import setup def", "\"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering", "#!/usr/bin/env python3 import os from setuptools import setup def read(fname):", "\"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering ::", "read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\",", "setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\",", "def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\",", "url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec", "from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(", "setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\",", "author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\",", "long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\":", "node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"],", "os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read()", "import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\",", "description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\",", "name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"),", "\"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic", "version=\"0.0.5\", author=\"<NAME>\", license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\",", "license=\"MIT\", author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"],", "packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec =", "entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic :: Scientific/Engineering :: Artificial Intelligence\"],", "implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\", \"numba\", \"gensim\",", "\"gensim\", \"click\", \"tqdm\"], python_requires=\">=3.6\", entry_points={\"console_scripts\": [\"fastnode2vec = fastnode2vec.cli:node2vec\"]}, classifiers=[\"Topic ::", "author_email=\"<EMAIL>\", description=\"Fast implementation of node2vec\", long_description=read(\"README.md\"), long_description_content_type=\"text/markdown\", url=\"https://github.com/louisabraham/fastnode2vec\", packages=[\"fastnode2vec\"], install_requires=[\"numpy\",", "setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=\"fastnode2vec\", version=\"0.0.5\", author=\"<NAME>\"," ]
[ "DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI =", "SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING =", "class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI =", "= True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION =", "class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir,", "= False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False", "False class ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig,", "False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' +", "DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS", "'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG", "True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False", "= False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///'", "SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS", "DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig )", "os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False", "= False class TestingConfig(Config): DEBUG = True TESTING = True", "os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG = True", "ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig", "'') DEBUG = False class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI", "Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config):", "= True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS =", "'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG", "basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG", "= True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir,", "= os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG =", "os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config):", "os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True", "True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db')", "TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION", "= False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig ) key", "TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///'", "os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '')", "PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG =", "+ os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG =", "SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class DevelopmentConfig(Config): DEBUG", "= False class ProductionConfig(Config): DEBUG = False config_by_name = dict(", "import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY',", "False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig ) key =", "+ os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False class", "= os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG =", "'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config): DEBUG = True TESTING", "= 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class TestingConfig(Config):", "True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False", "= 'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS =", "'sqlite:///' + os.path.join(basedir, 'flask_main.db') PRESERVE_CONTEXT_ON_EXCEPTION = False SQLALCHEMY_TRACK_MODIFICATIONS = False", "False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False config_by_name", "SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): DEBUG = False config_by_name =", "config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig, prod=ProductionConfig ) key = Config.SECRET_KEY", "class ProductionConfig(Config): DEBUG = False config_by_name = dict( dev=DevelopmentConfig, test=TestingConfig,", "DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db')", "class Config: SECRET_KEY = os.getenv('SECRET_KEY', '') DEBUG = False class", "SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'flask_main.db') SQLALCHEMY_TRACK_MODIFICATIONS = False class", "DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI = 'sqlite:///' +", "False class TestingConfig(Config): DEBUG = True TESTING = True SQLALCHEMY_DATABASE_URI" ]
[ "= chkusr.check_if_user_exists() # Error handling and JSON return if success:", "% self.user return success, ret_msg def main(): # Parsing argument", "chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling", "# Error handling and JSON return if success: module.exit_json(msg=ret_msg) else:", "= True ret_msg = 'User %s exists' % self.user except", "% self.user except KeyError: success = False ret_msg = 'User", "argument file module = AnsibleModule( argument_spec = dict( user =", "Parsing argument file module = AnsibleModule( argument_spec = dict( user", "handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if", "def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True ret_msg", "user): self.user = user # Check if user exists def", "module = AnsibleModule( argument_spec = dict( user = dict(required=True) )", "check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True ret_msg =", "exists' % self.user except KeyError: success = False ret_msg =", "dict(required=True) ) ) user = module.params.get('user') chkusr = User(user) success,", "self.user except KeyError: success = False ret_msg = 'User %s", "from ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user): self.user", "AnsibleModule( argument_spec = dict( user = dict(required=True) ) ) user", "= 'User %s does not exists' % self.user return success,", "KeyError: success = False ret_msg = 'User %s does not", "not exists' % self.user return success, ret_msg def main(): #", "ret_msg = 'User %s does not exists' % self.user return", "file module = AnsibleModule( argument_spec = dict( user = dict(required=True)", "ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user): self.user =", "= False ret_msg = 'User %s does not exists' %", ") user = module.params.get('user') chkusr = User(user) success, ret_msg =", "pwd.getpwnam(self.user) success = True ret_msg = 'User %s exists' %", "ret_msg = 'User %s exists' % self.user except KeyError: success", "def main(): # Parsing argument file module = AnsibleModule( argument_spec", "import pwd from ansible.module_utils.basic import AnsibleModule class User: def __init__(self,", "user = module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists()", "User: def __init__(self, user): self.user = user # Check if", "= pwd.getpwnam(self.user) success = True ret_msg = 'User %s exists'", "user = pwd.getpwnam(self.user) success = True ret_msg = 'User %s", "User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling and JSON", "user # Check if user exists def check_if_user_exists(self): try: user", "False ret_msg = 'User %s does not exists' % self.user", "main(): # Parsing argument file module = AnsibleModule( argument_spec =", "import AnsibleModule class User: def __init__(self, user): self.user = user", "# Check if user exists def check_if_user_exists(self): try: user =", "<reponame>djouani/Learning-Ansible-2.X-Third-Edition #!/usr/bin/env python import pwd from ansible.module_utils.basic import AnsibleModule class", "class User: def __init__(self, user): self.user = user # Check", "exists' % self.user return success, ret_msg def main(): # Parsing", "ret_msg = chkusr.check_if_user_exists() # Error handling and JSON return if", "Check if user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user)", "%s exists' % self.user except KeyError: success = False ret_msg", "return success, ret_msg def main(): # Parsing argument file module", "= dict(required=True) ) ) user = module.params.get('user') chkusr = User(user)", "= dict( user = dict(required=True) ) ) user = module.params.get('user')", "= User(user) success, ret_msg = chkusr.check_if_user_exists() # Error handling and", "self.user return success, ret_msg def main(): # Parsing argument file", "ret_msg def main(): # Parsing argument file module = AnsibleModule(", "does not exists' % self.user return success, ret_msg def main():", "AnsibleModule class User: def __init__(self, user): self.user = user #", "and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__", "= user # Check if user exists def check_if_user_exists(self): try:", "self.user = user # Check if user exists def check_if_user_exists(self):", "%s does not exists' % self.user return success, ret_msg def", "user = dict(required=True) ) ) user = module.params.get('user') chkusr =", "__init__(self, user): self.user = user # Check if user exists", "pwd from ansible.module_utils.basic import AnsibleModule class User: def __init__(self, user):", "module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() # Error", "exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success = True", "try: user = pwd.getpwnam(self.user) success = True ret_msg = 'User", "chkusr.check_if_user_exists() # Error handling and JSON return if success: module.exit_json(msg=ret_msg)", "'User %s exists' % self.user except KeyError: success = False", "success, ret_msg = chkusr.check_if_user_exists() # Error handling and JSON return", "python import pwd from ansible.module_utils.basic import AnsibleModule class User: def", "success, ret_msg def main(): # Parsing argument file module =", ") ) user = module.params.get('user') chkusr = User(user) success, ret_msg", "= AnsibleModule( argument_spec = dict( user = dict(required=True) ) )", "= 'User %s exists' % self.user except KeyError: success =", "def __init__(self, user): self.user = user # Check if user", "'User %s does not exists' % self.user return success, ret_msg", "except KeyError: success = False ret_msg = 'User %s does", "JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__ ==", "argument_spec = dict( user = dict(required=True) ) ) user =", "if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__ == \"__main__\": main()", "# Parsing argument file module = AnsibleModule( argument_spec = dict(", "#!/usr/bin/env python import pwd from ansible.module_utils.basic import AnsibleModule class User:", "return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg) if __name__ == \"__main__\":", "success = True ret_msg = 'User %s exists' % self.user", "dict( user = dict(required=True) ) ) user = module.params.get('user') chkusr", "= module.params.get('user') chkusr = User(user) success, ret_msg = chkusr.check_if_user_exists() #", "True ret_msg = 'User %s exists' % self.user except KeyError:", "user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success =", "Error handling and JSON return if success: module.exit_json(msg=ret_msg) else: module.fail_json(msg=ret_msg)", "success = False ret_msg = 'User %s does not exists'", "if user exists def check_if_user_exists(self): try: user = pwd.getpwnam(self.user) success" ]
[ "[https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok:", "lookup failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"],", "of the curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1]", "curie is empty, just return an empty string. This happens", "= _ontology_info_url(curie) if not url: return \"\" response = requests.get(url)", "Args: label: the label to find ontology terms for ontology:", "there is no # valid ontology value. if not curie:", "_double_encode(url): \"\"\"Double url encode a url. This is required by", "return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a curie.", "f\"Label {label} lookup failed, got status code {response.status_code}: {response.text}\" )", "is empty, just return an empty string. This happens when", "string. This happens when there is no # valid ontology", "much broader results Returns: list of (curie, label) tuples returned", "_ontology_name(curie): \"\"\"Get the name of the ontology from the curie,", "label in a submitted dataset, and you want to find", "def _ontology_value(curie): \"\"\"Get the id component of the curie, 0000001", "search. search provides much broader results Returns: list of (curie,", "id component of the curie, 0000001 from CL:0000001 for example.\"\"\"", "\"\"\"Exception for some problem with looking up ontology information.\"\"\" def", "quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a curie. This", "else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like", "like 'CL:1000413', get the label like 'endothelial cell of artery'\"\"\"", "This is useful when there is an existing label in", "in a submitted dataset, and you want to find an", "search in, cl or uberon or efo for example method:", "search provides much broader results Returns: list of (curie, label)", "return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for", "f\"Curie {curie} lookup failed, got status code {response.status_code}: {response.text}\" )", "provides much broader results Returns: list of (curie, label) tuples", "\"\"\"Double url encode a url. This is required by the", "list of (curie, label) tuples returned by OLS \"\"\" #", "the to make a GET to to get information about", "dataset, and you want to find an appropriate ontology term.", "label. This is useful when there is an existing label", "find ontology terms for ontology: the ontology to search in,", "ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a GET", "\"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\"", "a curie. This is a bit hopeful that they all", "f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with", "and you want to find an appropriate ontology term. Args:", "import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means", "broader results Returns: list of (curie, label) tuples returned by", "map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return", "This happens when there is no # valid ontology value.", "OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url)", "an empty string. This happens when there is no #", "there is an existing label in a submitted dataset, and", "encode a url. This is required by the OLS API.\"\"\"", "example method: select or search. search provides much broader results", "curie. This is a bit hopeful that they all map", "\"\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie", "that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\":", "a submitted dataset, and you want to find an appropriate", "url = _ontology_info_url(curie) if not url: return \"\" response =", "ontology value. if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\"", "if not url: return \"\" response = requests.get(url) if not", "failed, got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def", "terms for ontology: the ontology to search in, cl or", "failed, got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"])", "if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got", "if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie):", "= \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def _ontology_name(curie):", "of artery'\"\"\" url = _ontology_info_url(curie) if not url: return \"\"", "_iri(curie): \"\"\"Get the iri from a curie. This is a", "in, cl or uberon or efo for example method: select", "_ontology_value(curie): \"\"\"Get the id component of the curie, 0000001 from", "label to find ontology terms for ontology: the ontology to", "def _ontology_info_url(curie): \"\"\"Get the to make a GET to to", "something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the", "looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make", "CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the ontology from", "response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a", "up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a", "= f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise OntologyLookupError(", "\"\"\"Get the id component of the curie, 0000001 from CL:0000001", "# valid ontology value. if not curie: return \"\" else:", "all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\"", "the id component of the curie, 0000001 from CL:0000001 for", "by OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url", "got status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for", "example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of", "or uberon or efo for example method: select or search.", "return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413',", "about an ontology term.\"\"\" # If the curie is empty,", "just return an empty string. This happens when there is", "GET to to get information about an ontology term.\"\"\" #", "value. if not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def", "\"\"\"For a given curie like 'CL:1000413', get the label like", "method=\"select\"): \"\"\"Lookup candidate terms for a label. This is useful", "_ontology_info_url(curie): \"\"\"Get the to make a GET to to get", "label like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if", "# If the curie is empty, just return an empty", "f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get", "OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url =", "API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not", "import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like", "ontologies and the OLS.\"\"\" from urllib.parse import quote_plus import requests", "the label to find ontology terms for ontology: the ontology", "to to get information about an ontology term.\"\"\" # If", "UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id", ") return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms", "\"\"\"Get the to make a GET to to get information", "for example method: select or search. search provides much broader", "from the curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0]", "problem with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the", "not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got status", "from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url", "ontology term. Args: label: the label to find ontology terms", "CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode", "if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception):", "'CL:1000413', get the label like 'endothelial cell of artery'\"\"\" url", "some problem with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get", "url encode a url. This is required by the OLS", "class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up ontology", "not url: return \"\" response = requests.get(url) if not response.ok:", "or search. search provides much broader results Returns: list of", "from urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" #", "the OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT =", "\"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some", "or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the", "\"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get", "get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get the label", "= requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup", "\"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given curie", "a url. This is required by the OLS API.\"\"\" return", "not curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For", "cell of artery'\"\"\" url = _ontology_info_url(curie) if not url: return", "ontology: the ontology to search in, cl or uberon or", "of (curie, label) tuples returned by OLS \"\"\" # using", "_ontology_info_url(curie) if not url: return \"\" response = requests.get(url) if", "f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up", "is required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie):", "ontology to search in, cl or uberon or efo for", "hopeful that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) ==", "url: return \"\" response = requests.get(url) if not response.ok: raise", "example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url.", "get the label like 'endothelial cell of artery'\"\"\" url =", "'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if not url:", "(curie, label) tuples returned by OLS \"\"\" # using OLS", "API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from a", "for ontology: the ontology to search in, cl or uberon", "or efo for example method: select or search. search provides", "ontology term.\"\"\" # If the curie is empty, just return", "useful when there is an existing label in a submitted", "= requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label} lookup", "This is a bit hopeful that they all map to", "Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name", "valid ontology value. if not curie: return \"\" else: return", "get information about an ontology term.\"\"\" # If the curie", "bit hopeful that they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie)", "OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001 def", "a label. This is useful when there is an existing", "\"\"\"Methods for working with ontologies and the OLS.\"\"\" from urllib.parse", "is an existing label in a submitted dataset, and you", "uberon or efo for example method: select or search. search", "# Curie means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the", "purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class", "empty, just return an empty string. This happens when there", "the label like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie)", "like 'endothelial cell of artery'\"\"\" url = _ontology_info_url(curie) if not", "code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"):", "response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got status code", "the iri from a curie. This is a bit hopeful", "no # valid ontology value. if not curie: return \"\"", "required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get", "OntologyLookupError(Exception): \"\"\"Exception for some problem with looking up ontology information.\"\"\"", "to find an appropriate ontology term. Args: label: the label", "requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed,", "raise OntologyLookupError( f\"Curie {curie} lookup failed, got status code {response.status_code}:", "OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri from", "curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url. This is", "you want to find an appropriate ontology term. Args: label:", "ontology terms for ontology: the ontology to search in, cl", "results Returns: list of (curie, label) tuples returned by OLS", "def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label.", "\"\"\"Get the name of the ontology from the curie, CL", "raise OntologyLookupError( f\"Label {label} lookup failed, got status code {response.status_code}:", "# using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response", "name of the ontology from the curie, CL or UBERON", "quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something", "to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\"", "response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label {label}", "curie like 'CL:1000413', get the label like 'endothelial cell of", "a bit hopeful that they all map to purl.obolibrary.org\"\"\" if", "an existing label in a submitted dataset, and you want", "method: select or search. search provides much broader results Returns:", "ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label. This is", "code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for r in", "the curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def", "\"\"\"Get the iri from a curie. This is a bit", "to search in, cl or uberon or efo for example", "label) tuples returned by OLS \"\"\" # using OLS REST", "is a bit hopeful that they all map to purl.obolibrary.org\"\"\"", "response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got status code", "for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a", "information about an ontology term.\"\"\" # If the curie is", "This is required by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def", "the name of the ontology from the curie, CL or", "for some problem with looking up ontology information.\"\"\" def _ontology_info_url(curie):", "return \"\" response = requests.get(url) if not response.ok: raise OntologyLookupError(", "curie, 0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url):", "working with ontologies and the OLS.\"\"\" from urllib.parse import quote_plus", "label: the label to find ontology terms for ontology: the", "f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Label", "term.\"\"\" # If the curie is empty, just return an", "terms for a label. This is useful when there is", "for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component", "a given curie like 'CL:1000413', get the label like 'endothelial", "artery'\"\"\" url = _ontology_info_url(curie) if not url: return \"\" response", "with ontologies and the OLS.\"\"\" from urllib.parse import quote_plus import", "curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie):", "the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the iri", "return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem", "not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed, got status", "\"\"\"Lookup candidate terms for a label. This is useful when", "url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if not response.ok: raise", "lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate terms for a label. This", "def _double_encode(url): \"\"\"Double url encode a url. This is required", "term. Args: label: the label to find ontology terms for", "{response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup", "empty string. This happens when there is no # valid", "given curie like 'CL:1000413', get the label like 'endothelial cell", "url. This is required by the OLS API.\"\"\" return quote_plus(quote_plus(url))", "== \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for", "def get_ontology_label(curie): \"\"\"For a given curie like 'CL:1000413', get the", "{curie} lookup failed, got status code {response.status_code}: {response.text}\" ) return", "OntologyLookupError( f\"Label {label} lookup failed, got status code {response.status_code}: {response.text}\"", "of the ontology from the curie, CL or UBERON for", "submitted dataset, and you want to find an appropriate ontology", "an appropriate ontology term. Args: label: the label to find", "the ontology from the curie, CL or UBERON for example.\"\"\"", "return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a given", "to get information about an ontology term.\"\"\" # If the", "find an appropriate ontology term. Args: label: the label to", "if not response.ok: raise OntologyLookupError( f\"Label {label} lookup failed, got", "efo for example method: select or search. search provides much", "CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get", "a GET to to get information about an ontology term.\"\"\"", "response = requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie}", "is no # valid ontology value. if not curie: return", "lookup failed, got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"]", "return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception for some problem with looking", "return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double url encode a url. This", "OntologyLookupError( f\"Curie {curie} lookup failed, got status code {response.status_code}: {response.text}\"", "REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response = requests.get(url) if", "return curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of the", "make a GET to to get information about an ontology", "ontology from the curie, CL or UBERON for example.\"\"\" return", "iri from a curie. This is a bit hopeful that", "when there is an existing label in a submitted dataset,", "when there is no # valid ontology value. if not", "to make a GET to to get information about an", "like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of the ontology", "urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie", "curie.split(\":\")[0] def _ontology_value(curie): \"\"\"Get the id component of the curie,", "_ontology_name(curie) == \"EFO\": return f\"http://www.ebi.ac.uk/efo/EFO_{_ontology_value(curie)}\" return f\"http://purl.obolibrary.org/obo/{_ontology_name(curie)}_{_ontology_value(curie)}\" class OntologyLookupError(Exception): \"\"\"Exception", "component of the curie, 0000001 from CL:0000001 for example.\"\"\" return", "def _ontology_name(curie): \"\"\"Get the name of the ontology from the", "curie: return \"\" else: return f\"{OLS_API_ROOT}/ontologies/{_ontology_name(curie)}/terms/{_double_encode(_iri(curie))}\" def get_ontology_label(curie): \"\"\"For a", "with looking up ontology information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to", "existing label in a submitted dataset, and you want to", "and the OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT", "Returns: list of (curie, label) tuples returned by OLS \"\"\"", "the ontology to search in, cl or uberon or efo", "{label} lookup failed, got status code {response.status_code}: {response.text}\" ) return", "If the curie is empty, just return an empty string.", "happens when there is no # valid ontology value. if", "return an empty string. This happens when there is no", "candidate terms for a label. This is useful when there", "the curie, CL or UBERON for example.\"\"\" return curie.split(\":\")[0] def", "{response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\", method=\"select\"): \"\"\"Lookup candidate", "means something like CL:0000001 def _ontology_name(curie): \"\"\"Get the name of", "is useful when there is an existing label in a", "cl or uberon or efo for example method: select or", "information.\"\"\" def _ontology_info_url(curie): \"\"\"Get the to make a GET to", "OLS.\"\"\" from urllib.parse import quote_plus import requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\"", "an ontology term.\"\"\" # If the curie is empty, just", "for a label. This is useful when there is an", "tuples returned by OLS \"\"\" # using OLS REST API", "by the OLS API.\"\"\" return quote_plus(quote_plus(url)) def _iri(curie): \"\"\"Get the", "status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label, ontology=\"cl\",", "appropriate ontology term. Args: label: the label to find ontology", "for working with ontologies and the OLS.\"\"\" from urllib.parse import", "requests.get(url) if not response.ok: raise OntologyLookupError( f\"Curie {curie} lookup failed,", "to find ontology terms for ontology: the ontology to search", "{response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for r in response.json()[\"response\"][\"docs\"]]", "status code {response.status_code}: {response.text}\" ) return [(r[\"obo_id\"], r[\"label\"]) for r", "returned by OLS \"\"\" # using OLS REST API [https://www.ebi.ac.uk/ols/docs/api]", "0000001 from CL:0000001 for example.\"\"\" return curie.split(\":\")[1] def _double_encode(url): \"\"\"Double", "the curie is empty, just return an empty string. This", "def _iri(curie): \"\"\"Get the iri from a curie. This is", "want to find an appropriate ontology term. Args: label: the", "requests OLS_API_ROOT = \"http://www.ebi.ac.uk/ols/api\" # Curie means something like CL:0000001", "they all map to purl.obolibrary.org\"\"\" if _ontology_name(curie) == \"EFO\": return", "select or search. search provides much broader results Returns: list", "got status code {response.status_code}: {response.text}\" ) return response.json()[\"label\"] def lookup_candidate_term(label,", "from a curie. This is a bit hopeful that they", "using OLS REST API [https://www.ebi.ac.uk/ols/docs/api] url = f\"{OLS_API_ROOT}/{method}?q={quote_plus(label)}&ontology={ontology.lower()}\" response =" ]
[ "}] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered", "\"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] },", "aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None:", "IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import", "= get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**:", "GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2,", "inc. # All rights reserved. # # Redistribution and use", "materials provided with the distribution. # # THIS SOFTWARE IS", "*args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes a", "List filter objects **Tags**: survey **Examples** .. code-block:: http GET", "case, a metric and cohort have a connection # and", "EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView):", "#pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\"", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY", "get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a ``Matrix`` derived", "= ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs):", "# # 1. Redistributions of source code must retain the", "above copyright notice, # this list of conditions and the", "in the # documentation and/or other materials provided with the", "for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }]", "OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT", "\"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer", "code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\":", "extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination import", "# # Redistribution and use in source and binary forms,", "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,", "metric.tags, \\ \"filter '%s' is not tagged as a metric\"", "'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)}", "\"\" ], \"likely_metric\": \"\" } responds .. code-block:: json {", "assert 'metric' in metric.tags, \\ \"filter '%s' is not tagged", "matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return", "import PageNumberPagination from rest_framework import response as http from ..compat", "#pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL", "\"\"\" Create a fitler **Tags**: survey **Examples** .. code-block:: http", "cut = matrix.cut if not cohorts: # We don't have", "\"/ (%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts,", "accounts against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All", "('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter", "notice, # this list of conditions and the following disclaimer.", "code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json {", "in binary form must reproduce the above copyright # notice,", "PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE", "100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self): if", "} \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def", "return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous',", "\"\"\" Deletes a fitler **Tags**: survey **Examples** .. code-block:: http", "else: # If `matrix.cohorts is None`, the `cohorts` argument #", "= 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args,", "POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2,", "OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER", "def put(self, request, *args, **kwargs): \"\"\" Updates a fitler **Tags**:", "= self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if", "{\"scores\": scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix", "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score", "**Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block::", "result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset():", "request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**:", "cohorts aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages", "metric and cohort have a connection # and could have", "**Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block::", "Copyright (c) 2020, DjaoDjin inc. # All rights reserved. #", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #", "questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class", "/api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against all questions\",", "to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\"", "# override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter'", "/api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts against all", "documentation and/or other materials provided with the distribution. # #", "Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def", "*args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**:", "list of conditions and the following disclaimer in the #", "'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric", "question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / (", "some case, a metric and cohort have a connection #", "generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts aganist a", "\"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" search_fields", "\"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_question_serializer()", "] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs)", "scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self): if not", "look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri(", "of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: {", "public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result +=", "generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** .. code-block:: http", "NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE", "magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if", "includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions =", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR", "Many times people will use the same name to either", "[scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer(", "], \"likely_metric\": \"\" } ] } \"\"\" search_fields = ['tags']", "source and binary forms, with or without # modification, are", "(c) 2020, DjaoDjin inc. # All rights reserved. # #", "= {} if metric: assert 'metric' in metric.tags, \\ \"filter", "derived from *cohort*. Many times people will use the same", "a fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/", "get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(),", "\"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\",", "return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args,", "languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }]", "OrderedDict from django.db.models import F from django.http import Http404 from", "override in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def", "1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ],", "LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod", "json { \"count\": 2, previous: null, next: null, results: [", "http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request,", "nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return {\"scores\":", "django.db.models import F from django.http import Http404 from django.shortcuts import", ".. code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\":", "of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: {", "nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers *", "\"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\",", "likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try:", "serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def", "SUCH DAMAGE. import logging, re from collections import OrderedDict from", "SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination from", "# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY", "PageNumberPagination from rest_framework import response as http from ..compat import", "http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts", "# and could have the same name. for cohort in", "# documentation and/or other materials provided with the distribution. #", "\"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }]", "null, results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\",", "'metric' in metric.tags, \\ \"filter '%s' is not tagged as", "data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()),", "/api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\": \"All\",", "201 CREATED { \"slug\": \"all\", \"title\": \"All accounts against all", "'%s' is not tagged as a metric\" % str(metric) includes,", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF", "aganist a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response:", "*cohort*. Many times people will use the same name to", "= self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0:", "a queryset of `Account` ... cohorts = accounts result =", "+= [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return", "= 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def", "# We don't have any cohorts, let's show individual accounts", "pagination_class = EditableFilterPagination serializer_class = None # override in subclasses", "def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404(", "have any cohorts, let's show individual accounts instead. if cut:", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return", "], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView,", "= nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score", "* 100) \"\\ \"/ (%d * %d) = %f\", str(cohort),", "likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result +=", "\"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\",", "at magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug)", "= {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric,", "disclaimer. # 2. Redistributions in binary form must reproduce the", "\"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\":", "\"likely_metric\": \"\" } responds .. code-block:: json { \"slug\": \"all\",", "#pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric else:", "AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT,", "could have the same name. for cohort in val['cohorts']: likely_metric", "and binary forms, with or without # modification, are permitted", "} \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class", "\"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\",", "from rest_framework import response as http from ..compat import reverse", "\"title\": \"All accounts\", \"predicates\": [] }] } .. code-block:: http", "\"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self):", "= get_account_model().objects.all() scores = {} if metric: assert 'metric' in", "= matrix.cut if not cohorts: # We don't have any", "metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores", "serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create", "form must reproduce the above copyright # notice, this list", "(get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER =", "('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results',", "HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12", "\"All accounts against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\":", "This is an attempt at magic. \"\"\" likely_metric = None", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE", "fitler **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1", "scores for cohorts aganist a metric. **Examples**: .. code-block:: http", "GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions related", "generics from rest_framework.pagination import PageNumberPagination from rest_framework import response as", "None: accounts = get_account_model().objects.all() scores = {} if metric: assert", "EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else:", "**Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds", "\"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field", "2, previous: null, next: null, results: [ { \"slug\": \"all\",", "of source code must retain the above copyright notice, #", "LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``.", "/api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\", \"title\":", "lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all()", "view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data):", "= (%d * 100) \"\\ \"/ (%d * %d) =", "the system will magically switch between both meaning. This is", "not tagged as a metric\" % str(metric) includes, excludes =", "will use the same name to either mean a cohort", "a connection # and could have the same name. for", "\"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\",", "get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class", "THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY", "collections import OrderedDict from django.db.models import F from django.http import", "nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score})", "2020, DjaoDjin inc. # All rights reserved. # # Redistribution", "NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;", "queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation(", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL", "A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL", "of scores for cohorts aganist a metric. **Examples**: .. code-block::", "a list of single account objects. qs_accounts = [cohort] nb_accounts", "# this list of conditions and the following disclaimer. #", "try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass", "EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data)", "val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut':", "import generics from rest_framework.pagination import PageNumberPagination from rest_framework import response", "Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages", "class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts", "get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next',", "<= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def matrix(self):", "the same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug'])", "WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF", "def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table", "= self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores(", "\"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\",", "have the same name. for cohort in val['cohorts']: likely_metric =", "\"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class =", "**includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation", "reproduce the above copyright # notice, this list of conditions", "'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs):", "**Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds", "*args, **kwargs): \"\"\" Create a fitler **Tags**: survey **Examples** ..", "request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples**", "INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers", "\"\"\" List filter objects **Tags**: survey **Examples** .. code-block:: http", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR", "if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter(", "\"\" } responds .. code-block:: json { \"slug\": \"all\", \"title\":", "an attempt at magic. \"\"\" likely_metric = None look =", "cohorts, let's show individual accounts instead. if cut: includes, excludes", "a fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/", "/api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous:", "Create a fitler **Tags**: survey **Examples** .. code-block:: http POST", "URL to a ``Matrix`` derived from *cohort*. Many times people", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds", "matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric =", "HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\",", "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF", "cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is", "\"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look:", "**kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler", "cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else:", "else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix =", "str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions", "results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\":", "{ \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\":", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts,", "following conditions are met: # # 1. Redistributions of source", "same name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if", "cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())})", "from django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF", "from ..compat import reverse from ..mixins import MatrixMixin from ..models", "} \"\"\" pagination_class = EditableFilterPagination serializer_class = None # override", "return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug):", "EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and", "rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework import", "HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,", "FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT", "GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\",", "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,", "import reverse from ..mixins import MatrixMixin from ..models import Answer,", "get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404()", "\"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug'", "cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores =", "get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates", "disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request,", "\"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\"", "# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "= 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self,", "= {} val = { 'slug': metric.slug, 'title': metric.title, 'metric':", "\"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } Response:", "\"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\":", "= matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not", "POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against all", "have a connection # and could have the same name.", "questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All", "= 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args,", "score) assert score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores}", "\"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\":", "list of ``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response:", "account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts", "self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return", "self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() #", "cohorts = accounts result = [] scores = {} val", "\"slug\": \"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{ \"portfolio-a\":", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, #", "django.http import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import", "return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**:", "import response as http from ..compat import reverse from ..mixins", "cohort have a connection # and could have the same", "*args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric =", "any cohorts, let's show individual accounts instead. if cut: includes,", "\"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\":", "code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All", "\"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" },", "\"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field =", "= get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise", "\"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class = None", "MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED.", "let's show individual accounts instead. if cut: includes, excludes =", "'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self,", "\"title\": \"All accounts against all questions\", \"metric\": { \"slug\": \"all-questions\",", "null, next: null, results: [ { \"slug\": \"all\", \"title\": \"All\",", "Redistributions of source code must retain the above copyright notice,", ".. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json {", "nb_questions > 0: for cohort in cohorts: if isinstance(cohort, EditableFilter):", "= get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if", "of conditions and the following disclaimer. # 2. Redistributions in", "code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts", "re from collections import OrderedDict from django.db.models import F from", "cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,)))", "def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if", "matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts", "= logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**:", "in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts", "if not cohorts: # We don't have any cohorts, let's", "a fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/", "\"all\", \"title\": \"All accounts against all questions\", \"metric\": { \"slug\":", "OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; #", "None`, the `cohorts` argument # will be a list of", "\"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class", "**Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return", "or without # modification, are permitted provided that the following", "* 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s'", "'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self,", "Redistribution and use in source and binary forms, with or", "source code must retain the above copyright notice, # this", "the following disclaimer in the # documentation and/or other materials", "LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING", "reverse from ..mixins import MatrixMixin from ..models import Answer, Matrix,", "return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class", "code-block:: json { \"count\": 2, previous: null, next: null, results:", "], \"likely_metric\": \"\" } responds .. code-block:: json { \"slug\":", "Filtered list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/", "fitler **Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1", "12 } \"\"\" pagination_class = EditableFilterPagination serializer_class = None #", "cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from an", "{ \"slug\": \"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{", "related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\",", "# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "\"\"\" Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http", "metric: assert 'metric' in metric.tags, \\ \"filter '%s' is not", "EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return", "INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1", "sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions", "def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint:", "EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey", "a metric and cohort have a connection # and could", "accounts\", \"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer def", "**Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 ..", "excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts =", "= accounts result = [] scores = {} val =", "survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation", "rights reserved. # # Redistribution and use in source and", "}, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [", "\"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer", "metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some", "= Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100", "binary form must reproduce the above copyright # notice, this", "[{ \"slug\": \"languages\", \"title\": \"All cohorts for all questions\" \"scores\":{", "EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView):", "http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\",", "for cohorts aganist a metric. **Examples**: .. code-block:: http GET", "a metric\" % str(metric) includes, excludes = metric.as_kwargs() questions =", "= matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We", "*args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples** ..", "return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores", "If `matrix.cohorts is None`, the `cohorts` argument # will be", "= 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def", "ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT", "\"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class = MatrixSerializer", "all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\"", "0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes", "people will use the same name to either mean a", "EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** .. code-block::", "between both meaning. This is an attempt at magic. \"\"\"", "excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If", "get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers", "\"selector\": \"\" ], \"likely_metric\": \"\" } responds .. code-block:: json", "# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,", "with the distribution. # # THIS SOFTWARE IS PROVIDED BY", ".serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\"", "accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores", "**Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json", "/ ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d", "self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts:", "list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response:", "IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR #", "disclaimer in the # documentation and/or other materials provided with", "likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\":", "\"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class =", "\"\"\" A table of scores for cohorts aganist a metric.", "score = nb_correct_answers * 100 / ( nb_questions * nb_accounts)", "serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView):", "] } \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def", "request, *args, **kwargs): \"\"\" Create a fitler **Tags**: survey **Examples**", "{} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)})", "..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer", "is None: accounts = get_account_model().objects.all() scores = {} if metric:", "filter objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/", "[public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all()", "above copyright # notice, this list of conditions and the", "return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self,", "don't have any cohorts, let's show individual accounts instead. if", "accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {} public_scores.update(val)", "be a list of single account objects. qs_accounts = [cohort]", "= self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts", "as http from ..compat import reverse from ..mixins import MatrixMixin", "(INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT", "MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http", "Implementation Note: switch cohorts from an queryset # of `EditableFilter`", "%d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score", "@property def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter(", "result += [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update(", "``Matrix`` derived from *cohort*. Many times people will use the", "cohorts from an queryset # of `EditableFilter` to a queryset", "cohorts for all questions\" \"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", }", "F from django.http import Http404 from django.shortcuts import get_object_or_404 from", "in source and binary forms, with or without # modification,", "def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List", ".. code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All", "nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort): score}) return", "[ { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [", "class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block::", "of single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts)", "http POST /api/matrix/ { \"slug\": \"all\", \"title\": \"All accounts against", "**kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples** .. code-block::", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED", "matrix = self.matrix if matrix: metric = self.matrix.metric else: parts", "permitted provided that the following conditions are met: # #", "responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\":", "http from ..compat import reverse from ..mixins import MatrixMixin from", "cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\":", "list of ``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response:", "is None`, the `cohorts` argument # will be a list", "\"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path'", "\"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\":", "public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data,", "score}) return {\"scores\": scores} @property def matrix(self): if not hasattr(self,", "must reproduce the above copyright # notice, this list of", "+= [scores] if public_cohorts: public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\":", "self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView):", "('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**:", "MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils import", "\"predicates\": [] }] } .. code-block:: http POST /api/matrix/ {", "switch cohorts from an queryset # of `EditableFilter` to a", "accounts = get_account_model().objects.all() scores = {} if metric: assert 'metric'", "get_account_serializer() # Implementation Note: switch cohorts from an queryset #", "\"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView):", "OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR", "cohort_slug): \"\"\" Returns a URL to a ``Matrix`` derived from", "/api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\":", "json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [", "#pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def", "subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return", "if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except", "\"filter '%s' is not tagged as a metric\" % str(metric)", "this list of conditions and the following disclaimer. # 2.", "public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def", "NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF", "EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return", "# 1. Redistributions of source code must retain the above", "not cohorts: # We don't have any cohorts, let's show", "A table of scores for cohorts aganist a metric. **Examples**:", "def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns", "use in source and binary forms, with or without #", "the `cohorts` argument # will be a list of single", "for '%s' = (%d * 100) \"\\ \"/ (%d *", "cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] =", "**kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples**", "``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\":", "get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: ..", "= cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts", "{ \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\":", "nb_questions = len(questions) if nb_questions > 0: for cohort in", "import Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin", "PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\":", "and expect the system will magically switch between both meaning.", "EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE", "str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100 scores.update({str(cohort):", "queryset # of `EditableFilter` to a queryset of `Account` ...", "to a queryset of `Account` ... cohorts = accounts result", "accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch", "ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result)", "], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request,", "is an attempt at magic. \"\"\" likely_metric = None look", "matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer =", "self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for", "class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin,", "the # documentation and/or other materials provided with the distribution.", "self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not", "score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property def", "\"count\": 2, previous: null, next: null, results: [ { \"slug\":", "Note: switch cohorts from an queryset # of `EditableFilter` to", "logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: ..", "a metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{", "**Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds", "scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores]", "Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages", "code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block:: json { \"slug\":", "survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds ..", "a ``Matrix`` derived from *cohort*. Many times people will use", ".. code-block:: json { \"count\": 2, previous: null, next: null,", "= 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None,", "get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from", "# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE", "code must retain the above copyright notice, # this list", "args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request,", "scores = {} val = { 'slug': metric.slug, 'title': metric.title,", "\"\"\" pagination_class = EditableFilterPagination serializer_class = None # override in", "**kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter =", "\"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\":", "many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class", "Http404 from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from", "\"scores\":{ \"portfolio-a\": \"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class =", "and cohort have a connection # and could have the", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class =", "http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\":", "return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter", "['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\"", "THE POSSIBILITY OF SUCH DAMAGE. import logging, re from collections", "metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} #", "self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects", "('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\"", "http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions", "'_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use", "cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts =", "not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def", "import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer)", "pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix", "individual accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts", "assert score <= 100 scores.update({str(cohort): score}) return {\"scores\": scores} @property", "\"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination serializer_class", "scores} @property def matrix(self): if not hasattr(self, '_matrix'): self._matrix =", "http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()),", "if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric", "with or without # modification, are permitted provided that the", "import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics", "**includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts` argument", "= cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts()", "[cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers =", "is not tagged as a metric\" % str(metric) includes, excludes", "`Account` ... cohorts = accounts result = [] scores =", "(%d * 100) \"\\ \"/ (%d * %d) = %f\",", "@staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\"", "= len(questions) if nb_questions > 0: for cohort in cohorts:", "of `Account` ... cohorts = accounts result = [] scores", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" serializer_class", "CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN", "( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d *", "distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "[] }] } Response: 201 CREATED { \"slug\": \"all\", \"title\":", "instead. if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter(", "/api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All questions related to", "Response: { \"slug\": \"all\", \"title\": \"All accounts against all questions\",", "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,", "a cohort or a metric and expect the system will", "switch between both meaning. This is an attempt at magic.", "100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' =", "EditableFilterPagination serializer_class = None # override in subclasses lookup_field =", "\"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class", "if nb_questions > 0: for cohort in cohorts: if isinstance(cohort,", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\"", "SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH", "#pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all() scores =", "re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=(", "code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json {", "AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http", "attempt at magic. \"\"\" likely_metric = None look = re.match(r\"(\\S+)(-\\d+)\",", "USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE", "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100) \"\\ \"/", "django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework import", "\"likely_metric\": \"\" } ] } \"\"\" search_fields = ['tags'] serializer_class", "= None # override in subclasses lookup_field = 'slug' lookup_url_kwarg", "'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs):", "} \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self,", "likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return", "CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,", "result = [] scores = {} val = { 'slug':", "\"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1,", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\",", "CREATED { \"slug\": \"all\", \"title\": \"All accounts against all questions\",", "**kwargs): \"\"\" Deletes a fitler **Tags**: survey **Examples** .. code-block::", "or a metric and expect the system will magically switch", "get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of", "EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut", "objects **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1", "logging, re from collections import OrderedDict from django.db.models import F", "name to either mean a cohort or a metric and", "import MatrixMixin from ..models import Answer, Matrix, EditableFilter from ..utils", "} ] } \"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer", "..compat import reverse from ..mixins import MatrixMixin from ..models import", "in subclasses lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self):", "lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request,", "survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds ..", "INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF", "\"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg", "class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples** ..", "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR", "SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED", "BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR", "queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset,", "def get_queryset(self): return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\"", "from ..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter", "\"\" ], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\",", "parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first()", "accounts instead. if cut: includes, excludes = cut.as_kwargs() accounts =", "and use in source and binary forms, with or without", "\"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{", "get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a", "from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer,", "scores = {} if metric: assert 'metric' in metric.tags, \\", "either mean a cohort or a metric and expect the", "raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts =", "COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT,", "put(self, request, *args, **kwargs): \"\"\" Updates a fitler **Tags**: survey", "# Copyright (c) 2020, DjaoDjin inc. # All rights reserved.", "lookup_url_kwarg = 'editable_filter' def get_queryset(self): return EditableFilter.objects.all() def put(self, request,", "self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\"", "'%s' = (%d * 100) \"\\ \"/ (%d * %d)", "= EditableFilterPagination serializer_class = None # override in subclasses lookup_field", "hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self):", "\"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\":", "import logging, re from collections import OrderedDict from django.db.models import", "**Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\",", "from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView):", "* %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert", "public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: #", "public_scores = {} public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\":", "**Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block::", "``Question``. **Examples**: .. code-block:: http GET /api/matrix/ Response: { \"slug\":", "qs_accounts = accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`,", "if cut: includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes)", "code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json {", "TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY", "[ \"rank\": 1, \"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\":", "[] }] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return", "= EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create a", "\"\"\" Filtered list of ``EditableFilter``. **Examples**: .. code-block:: http GET", "self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric,", "THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF", "# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,", "are met: # # 1. Redistributions of source code must", "> 0: for cohort in cohorts: if isinstance(cohort, EditableFilter): includes,", "len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter(", "= EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut =", "includes, excludes = cut.as_kwargs() accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts", "both meaning. This is an attempt at magic. \"\"\" likely_metric", "STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING", "EditableFilterSerializer def post(self, request, *args, **kwargs): \"\"\" Create a fitler", "json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class =", "class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block::", "AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN", "in metric.tags, \\ \"filter '%s' is not tagged as a", "], \"likely_metric\": \"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\":", "responds .. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 }", "get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts", "[{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] }", "100) \"\\ \"/ (%d * %d) = %f\", str(cohort), nb_correct_answers,", "EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "forms, with or without # modification, are permitted provided that", "binary forms, with or without # modification, are permitted provided", "**Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\",", "# will be a list of single account objects. qs_accounts", "objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts >", "and/or other materials provided with the distribution. # # THIS", "metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix:", "cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if", "copyright # notice, this list of conditions and the following", "table of scores for cohorts aganist a metric. **Examples**: ..", "cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut", "\"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put(", "..mixins import MatrixMixin from ..models import Answer, Matrix, EditableFilter from", "\"All accounts\", \"predicates\": [] }] } Response: 201 CREATED {", "cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs()", "provided that the following conditions are met: # # 1.", "} \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class", "OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY", "EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import", "\"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } Response: 201", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO,", ".. code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\":", "#pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get(", "= Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all()", "get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__)", "\"\" }, { \"slug\": \"none\", \"title\": \"None\", \"tags\": \"\", \"predicates\":", "DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND", "class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block::", "PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY", "nb_correct_answers * 100 / ( nb_questions * nb_accounts) LOGGER.debug(\"score for", "isinstance(cohort, EditableFilter): includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes)", "} \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list", "measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 / ( nb_questions *", "not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate')", "\"title\": \"All accounts\", \"predicates\": [] }] } Response: 201 CREATED", "super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([", "the above copyright # notice, this list of conditions and", "Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for", "are permitted provided that the following conditions are met: #", "COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS", "def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to a ``Matrix``", "Retrieve a fitler **Tags**: survey **Examples** .. code-block:: http GET", "\"selector\": \"\" ], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation", "magically switch between both meaning. This is an attempt at", "def post(self, request, *args, **kwargs): \"\"\" Create a fitler **Tags**:", "TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF", "met: # # 1. Redistributions of source code must retain", "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A", "FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO", "ARISING IN ANY WAY OUT OF THE USE OF THIS", "GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for", "# All rights reserved. # # Redistribution and use in", "ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN", "= MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model =", "\"\\ \"/ (%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions,", "return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix =", "self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note: switch cohorts from", "\"None\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\":", "**kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView,", "code-block:: http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All", "an queryset # of `EditableFilter` to a queryset of `Account`", "HTTP/1.1 .. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\":", "..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer,", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR", "self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\"", "``Question``. **Examples**: .. code-block:: http GET /api/questions/languages Response: { \"slug\":", "Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All accounts against", "= None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric", "# Redistribution and use in source and binary forms, with", "DAMAGE. import logging, re from collections import OrderedDict from django.db.models", "responds .. code-block:: json { \"count\": 2, previous: null, next:", "\"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args,", "SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS", "the above copyright notice, # this list of conditions and", ".. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView,", "code-block:: http GET /api/questions/languages Response: { \"slug\": \"languages\", \"title\": \"All", "get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix:", "accounts\", \"predicates\": [] }] } Response: 201 CREATED { \"slug\":", "# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "conditions are met: # # 1. Redistributions of source code", "cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts =", "\"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self,", "slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix def get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self,", "cut, accounts=self.get_accounts())}) result += [scores] if public_cohorts: public_scores = {}", "EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples** .. code-block::", "Deletes a fitler **Tags**: survey **Examples** .. code-block:: http DELETE", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS", "expect the system will magically switch between both meaning. This", "def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count', self.page.paginator.count),", "provided with the distribution. # # THIS SOFTWARE IS PROVIDED", "\"title\": \"All accounts\", \"predicates\": [] }] } \"\"\" serializer_class =", "post(self, request, *args, **kwargs): \"\"\" Create a fitler **Tags**: survey", "\"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView):", "} \"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg =", "fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1", "SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR", "request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``.", "return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a URL to", "import F from django.http import Http404 from django.shortcuts import get_object_or_404", "\"operator\": \"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\":", "**kwargs): \"\"\" Create a fitler **Tags**: survey **Examples** .. code-block::", "if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts =", "return {\"scores\": scores} @property def matrix(self): if not hasattr(self, '_matrix'):", "], \"likely_metric\": \"\" } \"\"\" serializer_class = EditableFilterSerializer lookup_field =", "in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric", "} responds .. code-block:: json { \"slug\": \"all\", \"title\": \"All\",", "# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR #", "# modification, are permitted provided that the following conditions are", "http.Response(result) class EditableFilterQuerysetMixin(object): @staticmethod def get_queryset(): return EditableFilter.objects.all() class EditableFilterListAPIView(SearchableListMixin,", "request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None):", "MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A", "= generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs)", "USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request, *args, **kwargs):", "EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples** ..", "cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort have", "OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT", "queryset of `Account` ... cohorts = accounts result = []", "BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY", "tagged as a metric\" % str(metric) includes, excludes = metric.as_kwargs()", "\"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs)", "conditions and the following disclaimer in the # documentation and/or", "get_accounts(self): #pylint:disable=unused-argument,no-self-use return get_account_model().objects.all() def get_likely_metric(self, cohort_slug): \"\"\" Returns a", "{} if metric: assert 'metric' in metric.tags, \\ \"filter '%s'", "import OrderedDict from django.db.models import F from django.http import Http404", "def matrix(self): if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first()", "same name to either mean a cohort or a metric", "\"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds .. code-block::", "accounts\", \"predicates\": [] }] } .. code-block:: http POST /api/matrix/", "{ \"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\":", "self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1]) matrix", "None look = re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric =", "GET /api/matrix/ Response: { \"slug\": \"all\", \"title\": \"All accounts against", "EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return", "('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class", "scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result += [scores] if", "**Tags**: survey **Examples** .. code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\"", "that the following conditions are met: # # 1. Redistributions", "includes, excludes = cohort.as_kwargs() qs_accounts = accounts.filter( **includes).exclude(**excludes) else: #", "\"\" ], \"likely_metric\": \"\" } ] } \"\"\" search_fields =", "\"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post(", ".. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json", "}] } .. code-block:: http POST /api/matrix/ { \"slug\": \"all\",", "In some case, a metric and cohort have a connection", "EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list", "show individual accounts instead. if cut: includes, excludes = cut.as_kwargs()", "survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/ HTTP/1.1 .. code-block::", "'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In", "except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs):", "of conditions and the following disclaimer in the # documentation", "import EditableFilterSerializer, MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered", "the same name to either mean a cohort or a", "= re.match(r\"(\\S+)(-\\d+)\", cohort_slug) if look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart',", "copyright notice, # this list of conditions and the following", "lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def", "previous: null, next: null, results: [ { \"slug\": \"all\", \"title\":", "delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**: survey", "self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request,", "mean a cohort or a metric and expect the system", "\"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer()", "= self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation", "DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args,", "'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric,", "of `EditableFilter` to a queryset of `Account` ... cohorts =", "rest_framework.pagination import PageNumberPagination from rest_framework import response as http from", "\"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http GET", "# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging,", "LOGGER.debug(\"score for '%s' = (%d * 100) \"\\ \"/ (%d", "# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter =", "= likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut, accounts=self.get_accounts())}) result", "\"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request,", "\"\" } ] } \"\"\" search_fields = ['tags'] serializer_class =", "QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``. **Examples**: .. code-block:: http", "(%d * %d) = %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score)", "HTTP/1.1 responds .. code-block:: json { \"count\": 2, previous: null,", "HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR", "LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS", "\"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores] return http.Response(result) class EditableFilterQuerysetMixin(object):", "conditions and the following disclaimer. # 2. Redistributions in binary", "}] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg =", "'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a metric and cohort", "from collections import OrderedDict from django.db.models import F from django.http", "and the following disclaimer. # 2. Redistributions in binary form", "metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions", "will be a list of single account objects. qs_accounts =", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } responds ..", "\"slug\": \"languages\", \"title\": \"All questions related to languages\" \"predicates\":[{ \"operator\":", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request, *args,", "the distribution. # # THIS SOFTWARE IS PROVIDED BY THE", "OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE", "cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts = get_account_model().objects.all()", "> 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score =", "\"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } ..", "request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request,", "request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)),", "the following disclaimer. # 2. Redistributions in binary form must", "if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count()", "single account objects. qs_accounts = [cohort] nb_accounts = len(qs_accounts) if", "\"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ] }", "data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey", "ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY,", "following disclaimer. # 2. Redistributions in binary form must reproduce", "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED", "BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY,", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\"", "use the same name to either mean a cohort or", "cohort or a metric and expect the system will magically", "\"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\": \"\",", "request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging, re", "MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\" A table of scores for cohorts aganist", "metric. **Examples**: .. code-block:: http GET /api/matrix/languages Response: [{ \"slug\":", "from rest_framework import generics from rest_framework.pagination import PageNumberPagination from rest_framework", "else: accounts = self.get_accounts() cohort_serializer = get_account_serializer() # Implementation Note:", "for cohort in cohorts: if isinstance(cohort, EditableFilter): includes, excludes =", "{ 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts':", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }, {", "EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates a fitler", "against all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\",", "Returns a URL to a ``Matrix`` derived from *cohort*. Many", "from rest_framework.pagination import PageNumberPagination from rest_framework import response as http", "notice, this list of conditions and the following disclaimer in", "excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions)", "{\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result += [public_scores]", "\"slug\": \"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1,", "'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case,", "IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,", "[] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\":", "other materials provided with the distribution. # # THIS SOFTWARE", ".. code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\", \"title\":", "retain the above copyright notice, # this list of conditions", "= self.matrix if matrix: metric = self.matrix.metric else: parts =", "EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples** .. code-block::", "All rights reserved. # # Redistribution and use in source", "= EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self):", "\"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\"", "look: try: likely_metric = self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist:", "\"All accounts\", \"predicates\": [] }] } .. code-block:: http POST", "without # modification, are permitted provided that the following conditions", "questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\":", "nb_questions * nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100)", "DjaoDjin inc. # All rights reserved. # # Redistribution and", "MatrixSerializer LOGGER = logging.getLogger(__name__) class MatrixCreateAPIView(generics.ListCreateAPIView): \"\"\" Filtered list of", "* nb_accounts) LOGGER.debug(\"score for '%s' = (%d * 100) \"\\", "\"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\",", "OUT OF THE USE OF THIS SOFTWARE, EVEN IF #", "THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR", "# notice, this list of conditions and the following disclaimer", "[] }] } .. code-block:: http POST /api/matrix/ { \"slug\":", "} ] } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterListAPIView, self).post( request, *args,", "the following conditions are met: # # 1. Redistributions of", "public_scores.update(val) public_scores.update( {\"cohorts\": EditableFilterSerializer( public_cohorts, many=True).data, \"values\": self.aggregate_scores(metric, public_cohorts)}) result", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE", "this list of conditions and the following disclaimer in the", "to either mean a cohort or a metric and expect", "matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts:", "return super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve", "/api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs)", "\"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\", \"field\": \"text\", \"selector\":\"keepmatching\" }] }", "modification, are permitted provided that the following conditions are met:", "code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class", "*args, **kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples** ..", "\"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" } ]", "*args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey", "meaning. This is an attempt at magic. \"\"\" likely_metric =", "get_account_model().objects.all() scores = {} if metric: assert 'metric' in metric.tags,", "metric\" % str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter(", "None # override in subclasses lookup_field = 'slug' lookup_url_kwarg =", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED #", "Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers * 100 /", "likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix", "def delete(self, request, *args, **kwargs): \"\"\" Deletes a fitler **Tags**:", "\"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of", "len(questions) if nb_questions > 0: for cohort in cohorts: if", "import SearchableListMixin from rest_framework import generics from rest_framework.pagination import PageNumberPagination", "and could have the same name. for cohort in val['cohorts']:", "NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "reserved. # # Redistribution and use in source and binary", "connection # and could have the same name. for cohort", "`EditableFilter` to a queryset of `Account` ... cohorts = accounts", "cohorts: # We don't have any cohorts, let's show individual", "from django.db.models import F from django.http import Http404 from django.shortcuts", "OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR", "if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts,", "next: null, results: [ { \"slug\": \"all\", \"title\": \"All\", \"tags\":", "self.editable_filter)), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ]))", "fitler **Tags**: survey **Examples** .. code-block:: http POST /api/xia/matrix/filters/ HTTP/1.1", "GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json { \"slug\": \"all\",", "**Examples**: .. code-block:: http GET /api/matrix/ Response: { \"slug\": \"all\",", "questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if nb_questions >", "OF THE POSSIBILITY OF SUCH DAMAGE. import logging, re from", "\"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\"", "lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts,", "questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": []", "Http404() cohort_serializer = EditableFilterSerializer cohorts = matrix.cohorts.exclude(tags__contains='aggregate') public_cohorts = matrix.cohorts.filter(tags__contains='aggregate')", "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER", "super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list", "OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY", "http GET /api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "super(EditableFilterListAPIView, self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a", "to a ``Matrix`` derived from *cohort*. Many times people will", "all questions\", \"metric\": { \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\":", "**kwargs): #pylint:disable=unused-argument,too-many-locals matrix = self.matrix if matrix: metric = self.matrix.metric", "**kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``EditableFilter``. **Examples**: ..", "\"field\": \"text\", \"selector\":\"keepmatching\" }] } \"\"\" serializer_class = get_account_serializer() class", "serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model", "\"predicates\": [] }] } Response: 201 CREATED { \"slug\": \"all\",", "\"title\": \"All questions\", \"predicates\": [] }, \"cohorts\": [{ \"slug\": \"all-accounts\",", "\"selector\": \"\" ], \"likely_metric\": \"\" } \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView,", "\"\"\" search_fields = ['tags'] serializer_class = EditableFilterSerializer def post(self, request,", "super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset,", ".. code-block:: http GET /api/xia/matrix/filters/all/ HTTP/1.1 responds .. code-block:: json", "val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric'] = likely_metric scores.update(val)", "])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List filter objects **Tags**: survey **Examples**", "a URL to a ``Matrix`` derived from *cohort*. Many times", "\"\"\" List fitlers **Tags**: survey **Examples** .. code-block:: http GET", "EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args, **kwargs): #pylint:disable=unused-argument,too-many-locals", ".. code-block:: json { \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\"", "EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut), 'cohorts': cohort_serializer(many=True).to_representation(cohorts)} # In some case, a", "get_queryset(self): return self.get_serializer_class().Meta.model.objects.all() def get(self, request, *args, **kwargs): #pylint: disable=unused-argument", "\"\" ], \"likely_metric\": \"\" } ] } \"\"\" #pylint:disable=useless-super-delegation return", "self).post( request, *args, **kwargs) class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler", "self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def", "Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for all questions\"", "EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self, request, *args,", "= self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer = get_account_serializer()", "LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION)", "= accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the", "rest_framework import response as http from ..compat import reverse from", "self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of", "list of conditions and the following disclaimer. # 2. Redistributions", "survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds ..", "question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals", "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE", "system will magically switch between both meaning. This is an", "class EditableFilterListAPIView(SearchableListMixin, EditableFilterQuerysetMixin, generics.ListCreateAPIView): \"\"\" List fitlers **Tags**: survey **Examples**", "}] } Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All", "Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer cohorts", "accounts is None: accounts = get_account_model().objects.all() scores = {} if", "... cohorts = accounts result = [] scores = {}", "} .. code-block:: http POST /api/matrix/ { \"slug\": \"all\", \"title\":", "\"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } .. code-block::", "accounts result = [] scores = {} val = {", "{ \"created_at\": \"2020-01-01T00:00:00Z\", \"measured\": 12 } \"\"\" pagination_class = EditableFilterPagination", "} Response: 201 CREATED { \"slug\": \"all\", \"title\": \"All accounts", "<reponame>djaodjin/djaodjin-survey # Copyright (c) 2020, DjaoDjin inc. # All rights", ".. code-block:: json { \"slug\": \"all\", \"title\": \"All\", \"tags\": \"\",", "nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter(", "paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset(", "= view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self,", "Answer, Matrix, EditableFilter from ..utils import (get_account_model, get_account_serializer, get_question_serializer) from", "from *cohort*. Many times people will use the same name", "{} val = { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric),", "import (get_account_model, get_account_serializer, get_question_serializer) from .serializers import EditableFilterSerializer, MatrixSerializer LOGGER", "code-block:: http DELETE /api/xia/matrix/filters/all/ HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete(", "DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE", "AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED", "\"0.1\", \"portfolio-b\": \"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field", "%f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <= 100", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND", "}] } \"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all()", "\"\"\" Returns a URL to a ``Matrix`` derived from *cohort*.", "from ..models import Answer, Matrix, EditableFilter from ..utils import (get_account_model,", "class EditableFilterDetailAPIView(generics.RetrieveUpdateDestroyAPIView): \"\"\" Retrieve a fitler **Tags**: survey **Examples** ..", "reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def get(self,", "Redistributions in binary form must reproduce the above copyright #", "\"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\",", "request, *args, **kwargs) def delete(self, request, *args, **kwargs): \"\"\" Deletes", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;", "= len(qs_accounts) if nb_accounts > 0: nb_correct_answers = Answer.objects.filter( question__in=questions,", "\"\"\" Updates a fitler **Tags**: survey **Examples** .. code-block:: http", "if accounts is None: accounts = get_account_model().objects.all() scores = {}", "generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class", "name. for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric:", "as a metric\" % str(metric) includes, excludes = metric.as_kwargs() questions", "request, *args, **kwargs): \"\"\" Updates a fitler **Tags**: survey **Examples**", "\"\"\" serializer_class = EditableFilterSerializer lookup_field = 'slug' lookup_url_kwarg = 'editable_filter'", ".. code-block:: http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json", "Updates a fitler **Tags**: survey **Examples** .. code-block:: http PUT", "slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\"", "List fitlers **Tags**: survey **Examples** .. code-block:: http GET /api/xia/matrix/filters/", "accounts.filter( **includes).exclude(**excludes) else: # If `matrix.cohorts is None`, the `cohorts`", "= [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0: nb_correct_answers", "http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\":", "view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view)", "http GET /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"created_at\":", "= MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin, generics.RetrieveUpdateDestroyAPIView): \"\"\"", "self.get_next_link()), ('previous', self.get_previous_link()), ('results', data) ])) class EditableFilterObjectsAPIView(generics.ListAPIView): \"\"\" List", "response as http from ..compat import reverse from ..mixins import", "1. Redistributions of source code must retain the above copyright", "\"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class EditableFilterPagination(PageNumberPagination):", "OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON", "of ``EditableFilter``. **Examples**: .. code-block:: http GET /api/questions/languages Response: {", "= self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter, slug=parts[-1])", "/api/matrix/languages Response: [{ \"slug\": \"languages\", \"title\": \"All cohorts for all", "\"slug\": \"all\", \"title\": \"All accounts against all questions\", \"metric\": {", "lookup_field = 'slug' lookup_url_kwarg = 'editable_filter' def get_queryset(self): return self.get_serializer_class().Meta.model.objects.all()", "**includes).exclude(**excludes) nb_questions = len(questions) if nb_questions > 0: for cohort", "`matrix.cohorts is None`, the `cohorts` argument # will be a", "= { 'slug': metric.slug, 'title': metric.title, 'metric': EditableFilterSerializer().to_representation(metric), 'cut': EditableFilterSerializer().to_representation(cut),", "\"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\": \"\", \"operand\":", "metric and expect the system will magically switch between both", "# If `matrix.cohorts is None`, the `cohorts` argument # will", "from django.shortcuts import get_object_or_404 from extra_views.contrib.mixins import SearchableListMixin from rest_framework", "list of single account objects. qs_accounts = [cohort] nb_accounts =", "#pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).put( request, *args, **kwargs) def delete(self, request,", "serializer_class = None # override in subclasses lookup_field = 'slug'", "qs_accounts = [cohort] nb_accounts = len(qs_accounts) if nb_accounts > 0:", "a metric and expect the system will magically switch between", "THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF", "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #", "# Implementation Note: switch cohorts from an queryset # of", "likely_metric: cohort['likely_metric'] = likely_metric scores.update(val) scores.update({\"values\": self.aggregate_scores( metric, cohorts, cut,", "class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter", "metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is None: accounts", "*args, **kwargs) class EditableFilterPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): self.editable_filter", "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, #", "def aggregate_scores(self, metric, cohorts, cut=None, accounts=None): #pylint:disable=unused-argument,too-many-locals if accounts is", "self.request.build_absolute_uri( reverse('matrix_chart', args=( EditableFilter.objects.get(slug=look.group(1)).slug,))) except EditableFilter.DoesNotExist: pass return likely_metric def", "a fitler **Tags**: survey **Examples** .. code-block:: http PUT /api/xia/matrix/filters/all/", "following disclaimer in the # documentation and/or other materials provided", "HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER", "from extra_views.contrib.mixins import SearchableListMixin from rest_framework import generics from rest_framework.pagination", "argument # will be a list of single account objects.", "`cohorts` argument # will be a list of single account", "0: nb_correct_answers = Answer.objects.filter( question__in=questions, sample__account__in=qs_accounts).filter( measured=F('question__correct_answer')).count() score = nb_correct_answers", "self.matrix if matrix: metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/')", "{ \"count\": 2, previous: null, next: null, results: [ {", "MatrixSerializer lookup_field = 'slug' lookup_url_kwarg = 'path' question_model = get_question_serializer().Meta.model", "= [] scores = {} val = { 'slug': metric.slug,", "if not hasattr(self, '_matrix'): self._matrix = Matrix.objects.filter( slug=self.kwargs.get(self.matrix_url_kwarg)).first() return self._matrix", "metric = self.matrix.metric else: parts = self.kwargs.get(self.matrix_url_kwarg).split('/') metric = get_object_or_404(EditableFilter,", "= get_account_serializer() # Implementation Note: switch cohorts from an queryset", "Response: { \"slug\": \"languages\", \"title\": \"All questions related to languages\"", "\"0.5\", } }] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug'", "*args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return", "\"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\" }", "LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN", "http POST /api/xia/matrix/filters/ HTTP/1.1 responds .. code-block:: json { \"count\":", "% str(metric) includes, excludes = metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes)", "self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter',", "{ \"slug\": \"all-questions\", \"title\": \"All questions\", \"predicates\": [] }, \"cohorts\":", "if metric: assert 'metric' in metric.tags, \\ \"filter '%s' is", "\"\"\" serializer_class = MatrixSerializer def get_queryset(self): return Matrix.objects.all() class MatrixDetailAPIView(MatrixMixin,", "'path' question_model = get_question_serializer().Meta.model def aggregate_scores(self, metric, cohorts, cut=None, accounts=None):", "\\ \"filter '%s' is not tagged as a metric\" %", "2. Redistributions in binary form must reproduce the above copyright", "WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES", "We don't have any cohorts, let's show individual accounts instead.", "view=view) def get_paginated_response(self, data): return http.Response(OrderedDict([ ('editable_filter', EditableFilterSerializer().to_representation( self.editable_filter)), ('count',", "\"All questions related to languages\" \"predicates\":[{ \"operator\": \"contains\", \"operand\": \"language\",", "times people will use the same name to either mean", "matrix.cut if not cohorts: # We don't have any cohorts,", "OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED", "self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg]) return super(EditableFilterObjectsAPIView, self).get( request, *args,", "\"all\", \"title\": \"All\", \"tags\": \"\", \"predicates\": [ \"rank\": 1, \"operator\":", "must retain the above copyright notice, # this list of", "slug=parts[-1]) matrix = Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer", "return super(EditableFilterObjectsAPIView, self).get( request, *args, **kwargs) class AccountListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered", "return super(EditableFilterPagination, self).paginate_queryset( queryset, request, view=view) def get_paginated_response(self, data): return", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR #", "matrix.cohorts.filter(tags__contains='aggregate') cut = matrix.cut if not cohorts: # We don't", "def paginate_queryset(self, queryset, request, view=None): self.editable_filter = view.editable_filter return super(EditableFilterPagination,", "(INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS", "OF SUCH DAMAGE. import logging, re from collections import OrderedDict", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\"", "for cohort in val['cohorts']: likely_metric = self.get_likely_metric(cohort['slug']) if likely_metric: cohort['likely_metric']", "POSSIBILITY OF SUCH DAMAGE. import logging, re from collections import", "will magically switch between both meaning. This is an attempt", "[] scores = {} val = { 'slug': metric.slug, 'title':", "CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE)", "# In some case, a metric and cohort have a", "= %f\", str(cohort), nb_correct_answers, nb_questions, nb_accounts, score) assert score <=", "from an queryset # of `EditableFilter` to a queryset of", "accounts = self.get_accounts().filter( **includes).exclude(**excludes) else: accounts = self.get_accounts() cohort_serializer =", "IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS", "\"\", \"operand\": \"\", \"field\": \"\", \"selector\": \"\" ], \"likely_metric\": \"\"", "return EditableFilter.objects.all() def put(self, request, *args, **kwargs): \"\"\" Updates a", "and the following disclaimer in the # documentation and/or other", "HTTP/1.1 \"\"\" #pylint:disable=useless-super-delegation return super(EditableFilterDetailAPIView, self).delete( request, *args, **kwargs) class", "serializer_class = get_account_serializer() class QuestionListAPIView(EditableFilterObjectsAPIView): \"\"\" Filtered list of ``Question``.", "\"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": [] }] } \"\"\"", "}, \"cohorts\": [{ \"slug\": \"all-accounts\", \"title\": \"All accounts\", \"predicates\": []", "# of `EditableFilter` to a queryset of `Account` ... cohorts", "request, *args, **kwargs): #pylint: disable=unused-argument self.editable_filter = generics.get_object_or_404( EditableFilter.objects.all(), slug=self.kwargs[self.lookup_url_kwarg])", "} }] \"\"\" serializer_class = MatrixSerializer lookup_field = 'slug' lookup_url_kwarg", "# 2. Redistributions in binary form must reproduce the above", "= Matrix.objects.filter(slug=parts[0]).first() if not matrix: raise Http404() cohort_serializer = EditableFilterSerializer", "= metric.as_kwargs() questions = self.question_model.objects.filter( **includes).exclude(**excludes) nb_questions = len(questions) if" ]
[ "(label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error: print", "def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service =", "completed to obtain the new credentials. Returns: Credentials, the obtained", "'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials():", "service = discovery.build('gmail', 'v1', http=http) userId = 'me' labels =", "credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path)", "(label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if", "flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If", "\"\"\"Gets valid user credentials from storage. If nothing has been", "are invalid, the OAuth2 flow is completed to obtain the", "('An error occurred: %s' % error) def DeleteLabel(service, user_id, label_id):", "the stored credentials are invalid, the OAuth2 flow is completed", "errors from oauth2client import client from oauth2client import tools from", "print ('An error occurred: %s' % error) def main(): credentials", "from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()", "occurred: %s' % error) def main(): credentials = get_credentials() http", "%s - Label name: %s' % (label['id'], label['name'])) \"\"\" return", "or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if", "or if the stored credentials are invalid, the OAuth2 flow", "+ credential_path) return credentials def GetLabels(service, user_id): try: response =", "httplib2 import os import sys import pickle from apiclient import", "to ' + credential_path) return credentials def GetLabels(service, user_id): try:", "= credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId = 'me'", "apiclient import errors from oauth2client import client from oauth2client import", "% error) def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http())", "store = Storage(credential_path) credentials = store.get() if not credentials or", "label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted", "' + credential_path) return credentials def GetLabels(service, user_id): try: response", "import client from oauth2client import tools from oauth2client.file import Storage", "= os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir,", "import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError:", "not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path)", "with id: %s deleted successfully.' % label_id) except errors.HttpError as", "import errors from oauth2client import client from oauth2client import tools", "%s' % error) def main(): credentials = get_credentials() http =", "try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted successfully.'", "label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__ == '__main__': main()", "credentials to ' + credential_path) return credentials def GetLabels(service, user_id):", "nothing has been stored, or if the stored credentials are", "Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow", "stored credentials are invalid, the OAuth2 flow is completed to", "= 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid", "get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId", "errors.HttpError as error: print ('An error occurred: %s' % error)", "storage. If nothing has been stored, or if the stored", "with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to", "credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME", "os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path", "= GetLabels(service, userId) for label in labels: if (label['type'] ==", "If modifying these scopes, delete your previously saved credentials #", "import discovery from apiclient import errors from oauth2client import client", "only for compatibility with Python 2.6 credentials = tools.run(flow, store)", "not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent =", "import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None", "credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path =", "= response['labels'] \"\"\" for label in labels: print ('Label id:", "print ('Label id: %s - Label name: %s' % (label['id'],", "invalid, the OAuth2 flow is completed to obtain the new", "% error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print", "SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize'", "pickle from apiclient import discovery from apiclient import errors from", "user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s", "tools from oauth2client.file import Storage try: import argparse flags =", "# If modifying these scopes, delete your previously saved credentials", "main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail',", "import tools from oauth2client.file import Storage try: import argparse flags", "compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials", "as error: print ('An error occurred: %s' % error) def", "delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES =", "def get_credentials(): \"\"\"Gets valid user credentials from storage. If nothing", "'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials", "flags) else: # Needed only for compatibility with Python 2.6", "labels = response['labels'] \"\"\" for label in labels: print ('Label", "service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in labels: print", "http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId =", "# Needed only for compatibility with Python 2.6 credentials =", "is completed to obtain the new credentials. Returns: Credentials, the", "2.6 credentials = tools.run(flow, store) print('Storing credentials to ' +", "import sys import pickle from apiclient import discovery from apiclient", "import pickle from apiclient import discovery from apiclient import errors", "store, flags) else: # Needed only for compatibility with Python", "= APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else:", "os import sys import pickle from apiclient import discovery from", "= Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid:", "id: %s deleted successfully.' % label_id) except errors.HttpError as error:", "credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1',", "APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials", "label['name'])) \"\"\" return labels except errors.HttpError as error: print ('An", "Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags", "= os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir)", "previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE", "\"\"\" return labels except errors.HttpError as error: print ('An error", "occurred: %s' % error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id,", "response['labels'] \"\"\" for label in labels: print ('Label id: %s", "'v1', http=http) userId = 'me' labels = GetLabels(service, userId) for", "credentials from storage. If nothing has been stored, or if", "None # If modifying these scopes, delete your previously saved", "Label name: %s' % (label['id'], label['name'])) \"\"\" return labels except", "%s deleted successfully.' % label_id) except errors.HttpError as error: print", "credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if", "os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json')", "from storage. If nothing has been stored, or if the", "print ('Label with id: %s deleted successfully.' % label_id) except", "os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials =", "OAuth2 flow is completed to obtain the new credentials. Returns:", "= store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE,", "Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir =", "= discovery.build('gmail', 'v1', http=http) userId = 'me' labels = GetLabels(service,", "~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox", "discovery.build('gmail', 'v1', http=http) userId = 'me' labels = GetLabels(service, userId)", "apiclient import discovery from apiclient import errors from oauth2client import", "flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials", "from apiclient import errors from oauth2client import client from oauth2client", "print ('An error occurred: %s' % error) def DeleteLabel(service, user_id,", "CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets", "'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user", "userId) for label in labels: if (label['type'] == 'user'): print('Deleting", "service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id: %s deleted successfully.' %", "import os import sys import pickle from apiclient import discovery", "credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) userId = 'me' labels", "user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for", "tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials", "%s' % (label['id'], label['name'])) \"\"\" return labels except errors.HttpError as", "GetLabels(service, userId) for label in labels: if (label['type'] == 'user'):", "from oauth2client import client from oauth2client import tools from oauth2client.file", "oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except", "userId = 'me' labels = GetLabels(service, userId) for label in", "credentials = tools.run_flow(flow, store, flags) else: # Needed only for", "credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json'", "client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow,", "sys import pickle from apiclient import discovery from apiclient import", "= argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying", "ImportError: flags = None # If modifying these scopes, delete", "id=label_id).execute() print ('Label with id: %s deleted successfully.' % label_id)", "return credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels", "Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage. If", "else: # Needed only for compatibility with Python 2.6 credentials", "SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store,", "in labels: if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service,", "been stored, or if the stored credentials are invalid, the", "= tools.run(flow, store) print('Storing credentials to ' + credential_path) return", "if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent", "if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed", "credential_path) return credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute()", "import print_function import httplib2 import os import sys import pickle", "oauth2client import tools from oauth2client.file import Storage try: import argparse", "try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags =", "('An error occurred: %s' % error) def main(): credentials =", "store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)", "your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels'", "\"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not", "__future__ import print_function import httplib2 import os import sys import", "from oauth2client import tools from oauth2client.file import Storage try: import", "name: %s' % (label['id'], label['name'])) \"\"\" return labels except errors.HttpError", "- Label name: %s' % (label['id'], label['name'])) \"\"\" return labels", "If nothing has been stored, or if the stored credentials", "modifying these scopes, delete your previously saved credentials # at", "at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME =", "obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials')", "credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~')", "try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label", "successfully.' % label_id) except errors.HttpError as error: print ('An error", "'.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store", "labels: print ('Label id: %s - Label name: %s' %", "error: print ('An error occurred: %s' % error) def main():", "error: print ('An error occurred: %s' % error) def DeleteLabel(service,", "scopes, delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES", "to obtain the new credentials. Returns: Credentials, the obtained credential.", "= None # If modifying these scopes, delete your previously", "= os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if", "valid user credentials from storage. If nothing has been stored,", "= client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials =", "Returns: Credentials, the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir", "labels except errors.HttpError as error: print ('An error occurred: %s'", "response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in", "print_function import httplib2 import os import sys import pickle from", "if the stored credentials are invalid, the OAuth2 flow is", "('Label with id: %s deleted successfully.' % label_id) except errors.HttpError", "from apiclient import discovery from apiclient import errors from oauth2client", "argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None #", "the new credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir", "flow is completed to obtain the new credentials. Returns: Credentials,", "has been stored, or if the stored credentials are invalid,", "os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials", "argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None # If modifying these", "credentials are invalid, the OAuth2 flow is completed to obtain", "credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get()", "flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags)", "def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels']", "GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\"", "'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__ ==", "Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to '", "credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags:", "import httplib2 import os import sys import pickle from apiclient", "% label_id) except errors.HttpError as error: print ('An error occurred:", "the obtained credential. \"\"\" home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir,", "= 'me' labels = GetLabels(service, userId) for label in labels:", "for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing", "if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json') store =", "DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with id:", "os.path.join(credential_dir, 'gmail-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not", "\"\"\" for label in labels: print ('Label id: %s -", "%s' % error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute()", "credentials = store.get() if not credentials or credentials.invalid: flow =", "label in labels: print ('Label id: %s - Label name:", "error occurred: %s' % error) def main(): credentials = get_credentials()", "http=http) userId = 'me' labels = GetLabels(service, userId) for label", "== 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__", "oauth2client import client from oauth2client import tools from oauth2client.file import", "= 'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from", "obtain the new credentials. Returns: Credentials, the obtained credential. \"\"\"", "if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id'])", "user credentials from storage. If nothing has been stored, or", "('Label id: %s - Label name: %s' % (label['id'], label['name']))", "label_id) except errors.HttpError as error: print ('An error occurred: %s'", "label in labels: if (label['type'] == 'user'): print('Deleting label:', label['name'])", "error occurred: %s' % error) def DeleteLabel(service, user_id, label_id): try:", "APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: #", "store) print('Storing credentials to ' + credential_path) return credentials def", "labels: if (label['type'] == 'user'): print('Deleting label:', label['name']) DeleteLabel(service, userId,", "'Inbox Organize' def get_credentials(): \"\"\"Gets valid user credentials from storage.", "= 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Inbox Organize' def", "except errors.HttpError as error: print ('An error occurred: %s' %", "new credentials. Returns: Credentials, the obtained credential. \"\"\" home_dir =", "credentials def GetLabels(service, user_id): try: response = service.users().labels().list(userId=user_id).execute() labels =", "in labels: print ('Label id: %s - Label name: %s'", "# at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME", "error) def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service", "labels = GetLabels(service, userId) for label in labels: if (label['type']", "'me' labels = GetLabels(service, userId) for label in labels: if", "saved credentials # at ~/.credentials/gmail-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/gmail.labels' CLIENT_SECRET_FILE =", "these scopes, delete your previously saved credentials # at ~/.credentials/gmail-python-quickstart.json", "print('Deleting label:', label['name']) DeleteLabel(service, userId, label['id']) if __name__ == '__main__':", "def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label with", "discovery from apiclient import errors from oauth2client import client from", "= service.users().labels().list(userId=user_id).execute() labels = response['labels'] \"\"\" for label in labels:", "deleted successfully.' % label_id) except errors.HttpError as error: print ('An", "Needed only for compatibility with Python 2.6 credentials = tools.run(flow,", "except ImportError: flags = None # If modifying these scopes,", "flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only", "= tools.run_flow(flow, store, flags) else: # Needed only for compatibility", "for label in labels: if (label['type'] == 'user'): print('Deleting label:',", "id: %s - Label name: %s' % (label['id'], label['name'])) \"\"\"", "get_credentials(): \"\"\"Gets valid user credentials from storage. If nothing has", "return labels except errors.HttpError as error: print ('An error occurred:", "= get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http)", "the OAuth2 flow is completed to obtain the new credentials.", "tools.run_flow(flow, store, flags) else: # Needed only for compatibility with", "error) def DeleteLabel(service, user_id, label_id): try: service.users().labels().delete(userId=user_id, id=label_id).execute() print ('Label", "stored, or if the stored credentials are invalid, the OAuth2", "flags = None # If modifying these scopes, delete your", "from __future__ import print_function import httplib2 import os import sys", "client from oauth2client import tools from oauth2client.file import Storage try:", "for label in labels: print ('Label id: %s - Label", "home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir):", "print('Storing credentials to ' + credential_path) return credentials def GetLabels(service,", "% (label['id'], label['name'])) \"\"\" return labels except errors.HttpError as error:" ]
[ "## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32),", "obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE", "('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)),", "elif obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES,", "('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32),", "0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1:", "('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def", "('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES", "('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32),", "('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT", "ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)),", "('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64),", "('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32),", "('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ])", "obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision", "## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32),", "('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT", "('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64),", "== 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!')", "sys.exit() elif obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED", "obj.galaxies == 1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE", "ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug:", "('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)),", "('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)),", "]) def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision ==", "== 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision ==", "% obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision ==", "('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0: if", "('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32),", "elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1", "## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32),", "halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32),", "('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32),", "print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!' % obj.format_revision)", "('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)),", "('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32),", "('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32),", "('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies", "halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning halostruct2') return", "('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32),", "ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32),", "obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision == 0:", "HALO_FORMAT_REVISION=%d, if this is >1 email me!' % obj.format_revision) sys.exit()", "## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ##", "np import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)),", "('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2", "halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1", "elif obj.format_revision == 1: if obj.debug: print('returning halostruct1') return halostruct1", "halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32),", "('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64),", "('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32),", "np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32),", "('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64),", "== 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found", "('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64),", "sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halostruct1') return", "('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)),", "if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif", "('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32), ('type',np.int32),", "1: if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit()", "if obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR,", "2: if obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d,", "('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32),", "== 1: if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision", "('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)),", "('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64),", "PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning", "obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else:", "sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1') return", "('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32),", "ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 =", "('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64),", "ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug:", "print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is", "else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!' %", "print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if", "('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies ==", "def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision == 0:", "('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ##", "obj.format_revision == 1: if obj.debug: print('returning halostruct1') return halostruct1 elif", "me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1: if obj.format_revision", "('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32),", "('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ##", "]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)),", "obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision == 2: if", ">2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1:", "('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32),", "return halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning halostruct2')", "('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64),", "0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit()", "('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0:", "halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!'", "1: if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d,", "print('found HALO_FORMAT_REVISION=%d, if this is >1 email me!' % obj.format_revision)", "('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32),", "else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!' %", "import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)),", "('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ##", "= np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32),", "0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1:", "('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32),", "halostruct1') return halostruct1 elif obj.format_revision == 2: if obj.debug: print('returning", "halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email me!'", "('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32),", "if obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif", "print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is", "getRSformat(obj): if obj.galaxies == 0: if obj.format_revision == 0: print('OUTDATED", "('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64),", "## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) ## ROCKSTAR-GALAXIES ## halogalaxystruct1", "== 2: if obj.debug: print('returning halostruct2') return halostruct2 else: print('found", "('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32),", "('min_bulkvel_err',np.float32), ('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj):", "('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32),", "('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64),", "if obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if", "halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32),", "== 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision ==", "obj.format_revision == 2: if obj.debug: print('returning halostruct2') return halostruct2 else:", "obj.debug: print('returning halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this", "('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32),", "('av_density',np.float32), ]) def getRSformat(obj): if obj.galaxies == 0: if obj.format_revision", "numpy as np import sys ## ROCKSTAR ## halostruct1 =", "('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 =", "('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64),", "('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32),", "elif obj.format_revision == 2: if obj.debug: print('returning halostruct2') return halostruct2", "('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32),", "('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32)", "1: if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision ==", "('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32),", "## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32),", "## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32),", "('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32),", "this is >2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies", "if obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if", "('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64),", "('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ##", "UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halostruct1')", "('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32),", "ROCKSTAR-GALAXIES ## halogalaxystruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32),", "ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32),", "halostruct2') return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2", "]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32),", "if obj.debug: print('returning halostruct1') return halostruct1 elif obj.format_revision == 2:", "('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ])", "if this is >2 email me!' % obj.format_revision) sys.exit() elif", "== 0: if obj.format_revision == 0: print('OUTDATED ROCKSTAR, PLEASE UPDATE!')", "obj.format_revision == 0: print('OUTDATED ROCKSTAR-GALAXIES, PLEASE UPDATE!') sys.exit() elif obj.format_revision", "('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32), ('vrms',np.float32),", "## ALIGNMENT ('min_pos_err',np.float32), ('min_vel_err',np.float32), ('min_bulkvel_err',np.float32) ]) halostruct2 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)),", "import numpy as np import sys ## ROCKSTAR ## halostruct1", "as np import sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64),", "('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64),", "HALO_FORMAT_REVISION=%d, if this is >2 email me!' % obj.format_revision) sys.exit()", "ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32), ## ALIGNMENT", "('type',np.int32), ('sm',np.float32), ('gas',np.float32), ('bh',np.float32), ('peak_density',np.float32), ('av_density',np.float32), ]) def getRSformat(obj): if", "return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this is >1 email", "is >2 email me!' % obj.format_revision) sys.exit() elif obj.galaxies ==", "sys ## ROCKSTAR ## halostruct1 = np.dtype([('id',np.int64), ('pos',np.float32,(6,)), ('corevel',np.float32,(3,)), ('bulkvel',np.float32,(3,)),", "return halostruct2 else: print('found HALO_FORMAT_REVISION=%d, if this is >2 email", "('bulkvel',np.float32,(3,)), ('m',np.float32), ('r',np.float32), ('child_r',np.float32), ('vmax_r',np.float32), ('mgrav',np.float32), ('vmax',np.float32), ('rvmax',np.float32), ('rs',np.float32), ('klypin_rs',np.float32),", "print('OUTDATED ROCKSTAR, PLEASE UPDATE!') sys.exit() elif obj.format_revision == 1: if", "print('returning halostruct1') return halostruct1 elif obj.format_revision == 2: if obj.debug:", "('m_pe_d',np.float32), ('halfmass_radius',np.float32), #('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64),", "obj.debug: print('returning halogalaxystruct1') return halogalaxystruct1 else: print('found HALO_FORMAT_REVISION=%d, if this", "('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32),", "('vrms',np.float32), ('J',np.float32,(3,)), ('energy',np.float32), ('spin',np.float32), ('alt_m',np.float32,(4,)), ('Xoff',np.float32), ('Voff',np.float32), ('b_to_a',np.float32), ('c_to_a',np.float32), ('A',np.float32,(3,)),", "#('dummy1',np.float32), ## ALIGNMENT ('num_p',np.int64), ('num_child_particles',np.int64), ('p_start',np.int64), ('desc',np.int64), ('flags',np.int64), ('n_core',np.int64), ('dummy2',np.float32),", "UPDATE!') sys.exit() elif obj.format_revision == 1: if obj.debug: print('returning halogalaxystruct1')", "email me!' % obj.format_revision) sys.exit() elif obj.galaxies == 1: if", "('c_to_a',np.float32), ('A',np.float32,(3,)), ('b_to_a2',np.float32), ('c_to_a2',np.float32), ('A2',np.float32,(3,)), ('bullock_spin',np.float32), ('kin_to_pot',np.float32), ('m_pe_b',np.float32), ('m_pe_d',np.float32), ('dummy1',np.float32)," ]
[ "from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text", "\"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'],", "dest=\"ics_url\", help=\"The URL under which the ICS-file can be retrieved\",", "hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER", "deradicalise_ical(ics): \"\"\" :param ics: input file :type ics: str :return:", "\"new\" past events to the wiki archive page :param past_events:", "for the wiki :type wiki_user: str :param wiki_pw: password for", "file with remove radicale_headers \"\"\" deradicalised = \"\" for line", "+ \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site", "\"\"\" :return: The event's description :rtype: str \"\"\" links =", "Check if the event lies in the past :rtype: bool", "\" + self.location + \" || \" + self.description )", "provided with the package\") raise error return ics_url, file, wiki,", "ics import Calendar from mwclient import Site from dateutil.tz import", "description def __str__(self): \"\"\" :return: A wiki line describing the", "|| \" + self.start_time + \" || \" + self.location", "Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the", "location :rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", }", "for event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for", "= { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if", "\"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location: location =", ") parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the", "days_to_event(self): \"\"\" :return: Days to the start of the event", "def __init__(self, event): \"\"\" :param event: The event to be", "that were not added to the events page :type past_events:", "the past to the \"Termine\" Wiki page and appends past", "config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error: print(\"Please have", "end time :rtype: str \"\"\" end_date = \"\" if self.endtime", "Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine,", ":param past_events: the past events that were not added to", "= None wiki = None event = self.event if event.description:", "write and everything you edit WILL BE OVERWRITTEN Dieser Text", "+ '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args():", "retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\",", "str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return:", "last_table_position = index if str(event) in text: continue if year_header", "and appends past events to the \"Vergangene_Termine\" Site \"\"\" import", "metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which", "except locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics Event", "the wiki :type wiki_user: str :param wiki_pw: password for the", "Days to the start of the event :rtype: datetime.timedelta \"\"\"", "self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\"", "links = None wiki = None event = self.event if", "+ self.end_date + \" || \" + self.start_time + \"", "else: append_list = ( 3 * '\\n' + year_header +", "remove radicale_headers \"\"\" deradicalised = \"\" for line in ics.splitlines():", ":return: Days to the start of the event :rtype: datetime.timedelta", "The event to be evaluated :type event: ics.event.Event \"\"\" self.event", "event's description :rtype: str \"\"\" links = None wiki =", "bot, everything you write and everything you edit WILL BE", "Retrieve arguments from the command line, the config file respectively", "the event :rtype: str \"\"\" start_time = \" \" if", ":param wiki_pw: password for the wiki user :type wiki_pw: str", "wiki, debug = get_args() event_strings = [] past_events = []", "user for the wiki :type wiki_user: str :param wiki_pw: password", "error: print(\"Please have a look at the sample config provided", "self.start_time + \" || \" + self.location + \" ||", "as error: print(\"Please have a look at the sample config", "ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for", "and everything you edit WILL BE OVERWRITTEN Dieser Text ist", "style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER =", "<!-- This text is automatically generated by the ics2entropiawiki bot,", "to the wiki archive page :param past_events: the past events", "password for the wiki user :type wiki_pw: str :param wiki_archive:", ":return: location :rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\",", "ics Event and converts it to an entropia-wiki suitable form", "\"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki", "parser.parse_args() configfile = args.configfile ics_url = args.ics_url file = args.local_file", "ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the past to", "\"\"\" :return: The starting time of the event :rtype: str", "Site \"\"\" import locale import configparser import re import requests", "str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = (", "= self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki =", "deradicalised def main(): \"\"\" :return: None :rtype: None \"\"\" ics_url,", "parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\",", "wiki user :type wiki_pw: str :param wiki_archive: archive page :type", "file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" )", "\" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time", "describing the event :rtype: str \"\"\" return (\"| \" +", "\"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \",", "generiert. Alles was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN", ":rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\"", "\"\"\" <!-- This text is automatically generated by the ics2entropiawiki", "= event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve", "width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\",", "A wiki line describing the event :rtype: str \"\"\" return", "wiki_archive): \"\"\" Append the \"new\" past events to the wiki", "txtline == '|}': last_table_position = index if str(event) in text:", "]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the command", "'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug", "at the sample config provided with the package\") raise error", "\"\"\" import locale import configparser import re import requests from", "metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument(", "locale import configparser import re import requests from argparse import", "not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self):", "wiki_user: bot user for the wiki :type wiki_user: str :param", "def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past", "+ str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine", "past to the \"Termine\" Wiki page and appends past events", "self.location + \" || \" + self.description ) def append_past_events(past_events,", "/etc/ics2entropiawiki/config.ini Inserts events not in the past to the \"Termine\"", "event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location of an", "sample config provided with the package\") raise error return ics_url,", ":rtype: str \"\"\" links = None wiki = None event", "from argparse import ArgumentParser from datetime import timedelta, datetime from", "location(self): \"\"\" Retrieve the location of an event :return: location", "event.name return description def __str__(self): \"\"\" :return: A wiki line", "deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\" :return: None", "-*- \"\"\"ics2entropiawiki Read an ics file with the entropia events", "\"\\n\"+line return deradicalised def main(): \"\"\" :return: None :rtype: None", "evaluated :type event: ics.event.Event \"\"\" self.event = event self.begintime =", "location = self.event.location if location.lower() in locations.keys(): location = locations[location.lower()]", "arguments from the command line, the config file respectively :return:", "= 0 for event in past_events: year_header = \"== {}", "import ArgumentParser from datetime import timedelta, datetime from ics import", "wiki = None event = self.event if event.description: links =", "self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return: Days", "metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" )", "to an entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\"", ":return: The event's description :rtype: str \"\"\" links = None", "starting time of the event :rtype: str \"\"\" start_time =", "not event.name: description = \"N.A.\" else: description = event.name return", "wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER +", "= [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result =", "re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\"", "the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\",", "end_date = \"\" if self.endtime - self.begintime > timedelta(days=1): end_date", "event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self):", "event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0]", "index, txtline in enumerate(text): if txtline == '|}': last_table_position =", "OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch generiert. Alles", "|width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere", "metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument(", "page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge()", "= requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event", "__str__(self): \"\"\" :return: A wiki line describing the event :rtype:", "event): \"\"\" :param event: The event to be evaluated :type", "if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) )", "wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\")", "site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge() if __name__", "+ LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' ) text", "the entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts", "the events page :type past_events: list :param wiki_user: bot user", "continue if year_header in text: append_list = ( '\\n' +", "self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return: The event's", "wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in", "page :type past_events: list :param wiki_user: bot user for the", "pass class EntropiaEvent: \"\"\" Parses an ics Event and converts", "to the start of the event :rtype: datetime.timedelta \"\"\" return", ":param wiki_archive: archive page :type wiki_archive: str :return: None :rtype:", "None wiki = None event = self.event if event.description: links", "wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input file :type", "event :rtype: str \"\"\" start_time = \" \" if not", "return start_time @property def description(self): \"\"\" :return: The event's description", "self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the", "and converts it to an entropia-wiki suitable form \"\"\" def", ":return: file with remove radicale_headers \"\"\" deradicalised = \"\" for", "- datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if the", "help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The", "is_past_event(self): \"\"\" :return: Check if the event lies in the", "( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n'", "if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki:", "= \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property", "return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics:", "end_date @property def days_to_event(self): \"\"\" :return: Days to the start", "elif wiki: description = wiki[0] elif not event.name: description =", "\"\"\" return (\"| \" + self.begin_date + self.end_date + \"", "debug = get_args() event_strings = [] past_events = [] if", "def location(self): \"\"\" Retrieve the location of an event :return:", "- self.begintime > timedelta(days=1): end_date = \" - \" +", "form \"\"\" def __init__(self, event): \"\"\" :param event: The event", "past events to the \"Vergangene_Termine\" Site \"\"\" import locale import", ":type wiki_user: str :param wiki_pw: password for the wiki user", "the \"Termine\" Wiki page and appends past events to the", "= index if str(event) in text: continue if year_header in", "str \"\"\" return (\"| \" + self.begin_date + self.end_date +", "\"\"\" ics_url, file, wiki, debug = get_args() event_strings = []", "location = locations[location.lower()] return location @property def begin_date(self): \"\"\" :return:", "event_strings = [] past_events = [] if file: calendar =", "str :param wiki_pw: password for the wiki user :type wiki_pw:", "metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\"", "page and appends past events to the \"Vergangene_Termine\" Site \"\"\"", "\"\"\" :return: A wiki line describing the event :rtype: str", "= Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event", "+ TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER)", "! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !! Ort", "appends past events to the \"Vergangene_Termine\" Site \"\"\" import locale", "radicale_headers \"\"\" deradicalised = \"\" for line in ics.splitlines(): if", "wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description =", "page :param past_events: the past events that were not added", "text: append_list = ( '\\n' + LINE_SEPARATOR + str(event) )", "= \" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return", "wiki line describing the event :rtype: str \"\"\" return (\"|", "'|}': last_table_position = index if str(event) in text: continue if", "'\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR +", "wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events to the", ":param wiki_user: bot user for the wiki :type wiki_user: str", "raise error return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\"", "Text ist vom ics2entropiawiki bot automatisch generiert. Alles was hier", "parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file", "|| \" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive):", "@property def start_time(self): \"\"\" :return: The starting time of the", "an ics Event and converts it to an entropia-wiki suitable", "> timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\")", "if txtline == '|}': last_table_position = index if str(event) in", "wiki archive page :param past_events: the past events that were", "not added to the events page :type past_events: list :param", "\"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone()", "debug = args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try:", ":return: Entropia-Wiki formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a.,", "text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the", "the start of the event :rtype: datetime.timedelta \"\"\" return self.endtime", "= Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine:", "WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\"", "= 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda", "cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER", "\"\"\" Append the \"new\" past events to the wiki archive", "event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events,", "ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error:", "edit WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot", "+ LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else:", ":return: None :rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user,", "|width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links:", "with remove radicale_headers \"\"\" deradicalised = \"\" for line in", ") parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args =", "events that were not added to the events page :type", "user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\"", "'archive': args.wiki_archive, } debug = args.debug if configfile: config =", "event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if", "\" || \" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw,", "self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if", "page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from the command line,", "file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input file", "[[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8')", "not in line: deradicalised += \"\\n\"+line return deradicalised def main():", "str \"\"\" end_date = \"\" if self.endtime - self.begintime >", "event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR", "< timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting time", "from ics import Calendar from mwclient import Site from dateutil.tz", ":rtype: str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location", "'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug", "if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page", "termine = BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" +", "\" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def", "!! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\"", "wiki_archive: archive page :type wiki_archive: str :return: None :rtype: None", "description = \"N.A.\" else: description = event.name return description def", "everything you edit WILL BE OVERWRITTEN Dieser Text ist vom", "text: continue if year_header in text: append_list = ( '\\n'", "was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\"", "be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics", "to the \"Termine\" Wiki page and appends past events to", "\"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile", "@property def description(self): \"\"\" :return: The event's description :rtype: str", "events page :type past_events: list :param wiki_user: bot user for", "main(): \"\"\" :return: None :rtype: None \"\"\" ics_url, file, wiki,", ") text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve", "config file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\",", "Event and converts it to an entropia-wiki suitable form \"\"\"", "help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False", "calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin):", "requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in", "%d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return: Days to", "file with the entropia events and insert them in to", "args = parser.parse_args() configfile = args.configfile ics_url = args.ics_url file", "bool \"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\"", "( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \"", "tzlocal BOTWARNING = \"\"\" <!-- This text is automatically generated", "= self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return: The", ":rtype: str \"\"\" end_date = \"\" if self.endtime - self.begintime", "with the entropia events and insert them in to the", "elif not event.name: description = \"N.A.\" else: description = event.name", "description :rtype: str \"\"\" links = None wiki = None", "\"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location: location", "file, wiki, debug = get_args() event_strings = [] past_events =", "ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events,", "automatically generated by the ics2entropiawiki bot, everything you write and", "config provided with the package\") raise error return ics_url, file,", "them in to the entropia homepage wiki. Example: $ ics2entropiawiki.py", "user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE'", "the event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property", "= Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar", "\"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\"", "the ics2entropiawiki bot, everything you write and everything you edit", "\"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit'''", "\"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\",", "archive page :param past_events: the past events that were not", "past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in", "user :type wiki_pw: str :param wiki_archive: archive page :type wiki_archive:", "return deradicalised def main(): \"\"\" :return: None :rtype: None \"\"\"", "print(\"Please have a look at the sample config provided with", "\"\"\" end_date = \"\" if self.endtime - self.begintime > timedelta(days=1):", "event :rtype: str \"\"\" return (\"| \" + self.begin_date +", "\"\"\"ics2entropiawiki Read an ics file with the entropia events and", ") def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\"", "arguments from command line, config file :rtype: list \"\"\" parser", "return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check", "if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def", "!! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER", "Retrieve the location of an event :return: location :rtype: str", "event.name: description = \"N.A.\" else: description = event.name return description", "Inserts events not in the past to the \"Termine\" Wiki", "generated by the ics2entropiawiki bot, everything you write and everything", "EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event)", "site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for event in", "config[\"wiki\"] except KeyError as error: print(\"Please have a look at", ":rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self):", "\"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file can", "\"N.A.\" else: description = event.name return description def __str__(self): \"\"\"", "if termine: page.save(termine, \"Terminbot was here\") page.purge() if __name__ ==", "= args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url", "datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\"", "@property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype:", "end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype: str \"\"\"", "$ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not in the past", "%d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time", "help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page',", "Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\"", "wiki[0] elif not event.name: description = \"N.A.\" else: description =", "ics2entropiawiki bot automatisch generiert. Alles was hier manuell editiert, hinzugefügt", "ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\",", "style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !! Ort !!", "= Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text =", "==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline == '|}':", "+ str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text))", "args.wiki_archive, } debug = args.debug if configfile: config = configparser.ConfigParser()", "converts it to an entropia-wiki suitable form \"\"\" def __init__(self,", "import requests from argparse import ArgumentParser from datetime import timedelta,", "wiki_pw: str :param wiki_archive: archive page :type wiki_archive: str :return:", "in text: continue if year_header in text: append_list = (", "file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL", ":type event: ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone()", "configparser import re import requests from argparse import ArgumentParser from", ":param event: The event to be evaluated :type event: ics.event.Event", "start_time @property def description(self): \"\"\" :return: The event's description :rtype:", "args.debug if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url =", "dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki", "Wiki page and appends past events to the \"Vergangene_Termine\" Site", "self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\"", "= configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"]", "self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\",", "with the package\") raise error return ics_url, file, wiki, debug", "not in the past to the \"Termine\" Wiki page and", "wiki_pw: password for the wiki user :type wiki_pw: str :param", "utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with the entropia", "= config[\"wiki\"] except KeyError as error: print(\"Please have a look", "None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page =", "if location.lower() in locations.keys(): location = locations[location.lower()] return location @property", "debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page =", "Alles was hier manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN -->", "site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position =", "[] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else:", "else: description = event.name return description def __str__(self): \"\"\" :return:", "file = args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw,", "\"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\"", "past events that were not added to the events page", "path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\", help=\"The URL under", "Parses an ics Event and converts it to an entropia-wiki", "suitable form \"\"\" def __init__(self, event): \"\"\" :param event: The", "\"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass'])", "sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event:", "= \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum'''", "]+text[last_table_position:] else: append_list = ( 3 * '\\n' + year_header", "\"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument(", "event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index,", "= text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments from", "= page.text().split('\\n') last_table_position = 0 for event in past_events: year_header", "action=\"store_true\", default=False ) args = parser.parse_args() configfile = args.configfile ics_url", "return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return: The", "\" || \" + self.location + \" || \" +", "def main(): \"\"\" :return: None :rtype: None \"\"\" ics_url, file,", "style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit !!", "archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False )", "dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\",", "None :rtype: None \"\"\" ics_url, file, wiki, debug = get_args()", "\"\"\" return self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return:", "The starting time of the event :rtype: str \"\"\" start_time", "past_events: list :param wiki_user: bot user for the wiki :type", "site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text", "ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' + str(event) +", "{ \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \" if self.event.location:", "* '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR", "except KeyError as error: print(\"Please have a look at the", "|| \" + self.location + \" || \" + self.description", "\"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\",", "args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if", "parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\",", "+ \" || \" + self.description ) def append_past_events(past_events, wiki_user,", "be evaluated :type event: ics.event.Event \"\"\" self.event = event self.begintime", "bot user for the wiki :type wiki_user: str :param wiki_pw:", "Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev: ev.begin): event =", "wiki: description = wiki[0] elif not event.name: description = \"N.A.\"", "\"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration", "Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" )", "3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER + '\\n' +", "bot automatisch generiert. Alles was hier manuell editiert, hinzugefügt wird", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an", "ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime =", "append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events", "were not added to the events page :type past_events: list", "class EntropiaEvent: \"\"\" Parses an ics Event and converts it", "\"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive]", "= ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\",", "None :rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw)", "= event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location of", "URL under which the ICS-file can be retrieved\", metavar=\"URL\", )", "\"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]],", "parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file", "+ LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'],", "\" \" if self.event.location: location = self.event.location if location.lower() in", "else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text))", "# -*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file", "EntropiaEvent: \"\"\" Parses an ics Event and converts it to", "past_events: the past events that were not added to the", "'\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\"", "\"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene", "\"\"\" :return: None :rtype: None \"\"\" ics_url, file, wiki, debug", "links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description", "+ '\\n' + str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list,", "wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\"", "list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\",", "for event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event)", "str \"\"\" start_time = \" \" if not self.event.all_day: start_time", "parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" )", "timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return", "ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return", "start_time = self.begintime.strftime(\"%H:%M\") return start_time @property def description(self): \"\"\" :return:", "ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\"", "append_list = ( '\\n' + LINE_SEPARATOR + str(event) ) text", "line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised +=", "hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {|", "vom ics2entropiawiki bot automatisch generiert. Alles was hier manuell editiert,", "locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \" \"", "= args.configfile ics_url = args.ics_url file = args.local_file wiki =", "+ self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\" :return:", "return end_date @property def days_to_event(self): \"\"\" :return: Days to the", "cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER =", "not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else:", "location.lower() in locations.keys(): location = locations[location.lower()] return location @property def", "print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']]", "page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for", "lies in the past :rtype: bool \"\"\" return self.days_to_event <", "\" if self.event.location: location = self.event.location if location.lower() in locations.keys():", "formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property", "import timedelta, datetime from ics import Calendar from mwclient import", ") else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING", "coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with the", "entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\" :param event:", "@property def location(self): \"\"\" Retrieve the location of an event", "ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" +", "'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics", "the package\") raise error return ics_url, file, wiki, debug def", "in the past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0)", "try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as", "\"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\"", "in the past to the \"Termine\" Wiki page and appends", "to be evaluated :type event: ics.event.Event \"\"\" self.event = event", "This text is automatically generated by the ics2entropiawiki bot, everything", "everything you write and everything you edit WILL BE OVERWRITTEN", "\"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\"", "in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline", "an entropia-wiki suitable form \"\"\" def __init__(self, event): \"\"\" :param", "the past events that were not added to the events", "'\\n' + str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:]", "self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return location", "parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\",", "Read an ics file with the entropia events and insert", "ArgumentParser from datetime import timedelta, datetime from ics import Calendar", "line describing the event :rtype: str \"\"\" return (\"| \"", ":rtype: str \"\"\" start_time = \" \" if not self.event.all_day:", "args.ics_url file = args.local_file wiki = { 'user': args.wiki_user, 'pass':", "command line, the config file respectively :return: Parsed arguments from", "\"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\",", "class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum", "for the wiki user :type wiki_pw: str :param wiki_archive: archive", "event: The event to be evaluated :type event: ics.event.Event \"\"\"", "in to the entropia homepage wiki. Example: $ ics2entropiawiki.py --config", "= event.name return description def __str__(self): \"\"\" :return: A wiki", ":return: The starting time of the event :rtype: str \"\"\"", "line, config file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument(", "ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\"", ":type wiki_archive: str :return: None :rtype: None \"\"\" site =", ":return: None :rtype: None \"\"\" ics_url, file, wiki, debug =", "= BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings)", "TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if", "re import requests from argparse import ArgumentParser from datetime import", "the \"new\" past events to the wiki archive page :param", "\"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile =", "can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local", "start_time(self): \"\"\" :return: The starting time of the event :rtype:", "event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki", "wiki_user: str :param wiki_pw: password for the wiki user :type", "dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's", "and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description =", "style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = (", "under which the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument(", "{| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort'''", "parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument(", "ics: input file :type ics: str :return: file with remove", "time :rtype: str \"\"\" end_date = \"\" if self.endtime -", "the wiki archive page :param past_events: the past events that", "+ \" || \" + self.location + \" || \"", ":rtype: None \"\"\" site = Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page", "border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\"", "homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events not", "str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine =", "\"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location = \"", "@property def days_to_event(self): \"\"\" :return: Days to the start of", "if the event lies in the past :rtype: bool \"\"\"", "time of the event :rtype: str \"\"\" start_time = \"", "None event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description)", "requests from argparse import ArgumentParser from datetime import timedelta, datetime", "insert them in to the entropia homepage wiki. Example: $", "import Calendar from mwclient import Site from dateutil.tz import tzlocal", "\" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL,", "dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args() configfile = args.configfile", "+ '\\n' + LINE_SEPARATOR + '\\n' + str(event) + '\\n|}'", "import tzlocal BOTWARNING = \"\"\" <!-- This text is automatically", "the config file respectively :return: Parsed arguments from command line,", "+ year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n'", "\" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self): \"\"\"", "= re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and", "description = event.name return description def __str__(self): \"\"\" :return: A", "year_header in text: append_list = ( '\\n' + LINE_SEPARATOR +", "command line, config file :rtype: list \"\"\" parser = ArgumentParser()", ":param ics: input file :type ics: str :return: file with", "\"+event.name+\"]\" elif wiki: description = wiki[0] elif not event.name: description", "LINE_SEPARATOR + str(event) ) else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive'])", "__init__(self, event): \"\"\" :param event: The event to be evaluated", "you write and everything you edit WILL BE OVERWRITTEN Dieser", "past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result", "wiki_user, wiki_pw, wiki_archive): \"\"\" Append the \"new\" past events to", "error return ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param", "LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list", "def days_to_event(self): \"\"\" :return: Days to the start of the", "description(self): \"\"\" :return: The event's description :rtype: str \"\"\" links", "import Site from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!--", "str :return: file with remove radicale_headers \"\"\" deradicalised = \"\"", "begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype: str \"\"\"", "\"\"\" :return: Entropia-Wiki formatted begin time :rtype: str \"\"\" return", "datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return: Check if the event", "to the entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini", "'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return deradicalised def", "to the \"Vergangene_Termine\" Site \"\"\" import locale import configparser import", "= event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def", "timedelta, datetime from ics import Calendar from mwclient import Site", "= site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0 for event", "@property def is_past_event(self): \"\"\" :return: Check if the event lies", "= wiki[0] elif not event.name: description = \"N.A.\" else: description", "|width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]]", "self.event.location: location = self.event.location if location.lower() in locations.keys(): location =", "\"\"\" :return: Days to the start of the event :rtype:", "added to the events page :type past_events: list :param wiki_user:", "\" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\") return start_time @property", "events to the \"Vergangene_Termine\" Site \"\"\" import locale import configparser", "index if str(event) in text: continue if year_header in text:", "last_table_position = 0 for event in past_events: year_header = \"==", "help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE'", "\"\"\" :return: Check if the event lies in the past", "args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if configfile: config", "formatted end time :rtype: str \"\"\" end_date = \"\" if", "datetime from ics import Calendar from mwclient import Site from", "editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\"", "The event's description :rtype: str \"\"\" links = None wiki", "wiki :type wiki_user: str :param wiki_pw: password for the wiki", "0 for event in past_events: year_header = \"== {} ==\".format(event.endtime.strftime('%Y'))", ") parser.add_argument( \"-f\", \"--file\", dest=\"local_file\", help=\"Local ics file\", metavar=\"FILE\" )", "ist vom ics2entropiawiki bot automatisch generiert. Alles was hier manuell", "def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype: str", "if str(event) in text: continue if year_header in text: append_list", "have a look at the sample config provided with the", "ics file with the entropia events and insert them in", "TABLE_FOOTER = ( \"|}\", \"\\n\", \"Weitere Links: [[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit", "\"Vergangene_Termine\" Site \"\"\" import locale import configparser import re import", "import configparser import re import requests from argparse import ArgumentParser", "def get_args(): \"\"\" Retrieve arguments from the command line, the", "= ( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER +", "debug def deradicalise_ical(ics): \"\"\" :param ics: input file :type ics:", "== '|}': last_table_position = index if str(event) in text: continue", "site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was", "KeyError as error: print(\"Please have a look at the sample", "event lies in the past :rtype: bool \"\"\" return self.days_to_event", "border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !!", "{} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline ==", "= ( '\\n' + LINE_SEPARATOR + str(event) ) text =", "calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8'", "is automatically generated by the ics2entropiawiki bot, everything you write", "\"\"\" deradicalised = \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:'", "the wiki user :type wiki_pw: str :param wiki_archive: archive page", "path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot", "manuell editiert, hinzugefügt wird WIRD ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER =", "+ self.start_time + \" || \" + self.location + \"", "\" + self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\"", "Append the \"new\" past events to the wiki archive page", "\"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\",", "[[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error:", "Datum !! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\ \"\"\"", "Entropia-Wiki formatted end time :rtype: str \"\"\" end_date = \"\"", "mwclient import Site from dateutil.tz import tzlocal BOTWARNING = \"\"\"", "- \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date @property def days_to_event(self):", "str :param wiki_archive: archive page :type wiki_archive: str :return: None", "= locations[location.lower()] return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki", "respectively :return: Parsed arguments from command line, config file :rtype:", "+ \"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug:", "= self.event.location if location.lower() in locations.keys(): location = locations[location.lower()] return", "= site.pages[wiki['page']] if termine: page.save(termine, \"Terminbot was here\") page.purge() if", "\"\"\" start_time = \" \" if not self.event.all_day: start_time =", "BOTWARNING = \"\"\" <!-- This text is automatically generated by", "dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki", "= config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError as error: print(\"Please", "start of the event :rtype: datetime.timedelta \"\"\" return self.endtime -", "= re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description = \"[\"+links[0]+\"", ":type ics: str :return: file with remove radicale_headers \"\"\" deradicalised", "of the event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal())", "if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding", "cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" |", "else: past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING +", "class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\" |width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung'''", ":type past_events: list :param wiki_user: bot user for the wiki", "\"\\n\" + \"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine)", "\"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\",", "ics_url = args.ics_url file = args.local_file wiki = { 'user':", "\"\"\" Retrieve arguments from the command line, the config file", "str \"\"\" locations = { \"entropia\": \"[[Anfahrt|Entropia]]\", } location =", "ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\"", "\"\"\" :return: Entropia-Wiki formatted end time :rtype: str \"\"\" end_date", "} location = \" \" if self.event.location: location = self.event.location", "self.days_to_event < timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting", ") LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass", "file respectively :return: Parsed arguments from command line, config file", "str(event) in text: continue if year_header in text: append_list =", "year_header = \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text):", "if event.description: links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description)", "Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding = 'utf-8' calendar =", "def deradicalise_ical(ics): \"\"\" :param ics: input file :type ics: str", "= \"\"\" <!-- This text is automatically generated by the", "help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\",", "\"Termine\" Wiki page and appends past events to the \"Vergangene_Termine\"", "\", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR =", ":rtype: None \"\"\" ics_url, file, wiki, debug = get_args() event_strings", "dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\", dest=\"ics_url\",", "Entropia-Wiki formatted begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\")", "'\\n' + LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' )", "import locale import configparser import re import requests from argparse", "[[Vorlage:Termine|Termine]] \", \"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR", "package\") raise error return ics_url, file, wiki, debug def deradicalise_ical(ics):", "def description(self): \"\"\" :return: The event's description :rtype: str \"\"\"", "self.end_date + \" || \" + self.start_time + \" ||", "line, the config file respectively :return: Parsed arguments from command", "+ \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de',", "+ \" || \" + self.start_time + \" || \"", "TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\"", "description = \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif", "past events to the wiki archive page :param past_events: the", "Calendar from mwclient import Site from dateutil.tz import tzlocal BOTWARNING", "page.text().split('\\n') last_table_position = 0 for event in past_events: year_header =", "append_list = ( 3 * '\\n' + year_header + ARCHIVE_TABLE_HEADER", "if configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"]", "config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki =", "None \"\"\" ics_url, file, wiki, debug = get_args() event_strings =", "= \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent:", "= [] past_events = [] if file: calendar = Calendar(deradicalise_ical(open(file).read()))", "try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses", "(\"| \" + self.begin_date + self.end_date + \" || \"", "= get_args() event_strings = [] past_events = [] if file:", "page.save(termine, \"Terminbot was here\") page.purge() if __name__ == '__main__': main()", "termine: page.save(termine, \"Terminbot was here\") page.purge() if __name__ == '__main__':", "return (\"| \" + self.begin_date + self.end_date + \" ||", "begin time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def", "entropia events and insert them in to the entropia homepage", "} debug = args.debug if configfile: config = configparser.ConfigParser() config.read(configfile)", "| Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\"", "past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property def", "def start_time(self): \"\"\" :return: The starting time of the event", "[] if file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url)", "= ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\",", "path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position", "enumerate(text): if txtline == '|}': last_table_position = index if str(event)", "ics2entropiawiki bot, everything you write and everything you edit WILL", "file :rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\",", "LINE_SEPARATOR + '\\n' + str(event) + '\\n|}' ) text =", "wiki = config[\"wiki\"] except KeyError as error: print(\"Please have a", "a look at the sample config provided with the package\")", "help=\"Local ics file\", metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\",", "= \" \" if self.event.location: location = self.event.location if location.lower()", ") parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki user's password\", metavar=\"WIKIPW\" ) parser.add_argument(", "events and insert them in to the entropia homepage wiki.", "in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if not", "\"\".join(event_strings) + \"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site =", "self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted end", "it to an entropia-wiki suitable form \"\"\" def __init__(self, event):", "events not in the past to the \"Termine\" Wiki page", "\"\" if self.endtime - self.begintime > timedelta(days=1): end_date = \"", "= \"\" if self.endtime - self.begintime > timedelta(days=1): end_date =", "event :rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def", "links = re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links", "if year_header in text: append_list = ( '\\n' + LINE_SEPARATOR", "config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except KeyError", "args.configfile ics_url = args.ics_url file = args.local_file wiki = {", "\"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\"", "location of an event :return: location :rtype: str \"\"\" locations", "event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR + str(event) ) else: past_events.append(event)", ") args = parser.parse_args() configfile = args.configfile ics_url = args.ics_url", "from the command line, the config file respectively :return: Parsed", "= \"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif not", "event.description) if links and event.name: description = \"[\"+links[0]+\" \"+event.name+\"]\" elif", "events to the wiki archive page :param past_events: the past", "\"\"\" :param event: The event to be evaluated :type event:", "import re import requests from argparse import ArgumentParser from datetime", "\"\"\" Parses an ics Event and converts it to an", "for index, txtline in enumerate(text): if txtline == '|}': last_table_position", "text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 *", "Dieser Text ist vom ics2entropiawiki bot automatisch generiert. Alles was", "text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 * '\\n' +", "= args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page':", "archive page :type wiki_archive: str :return: None :rtype: None \"\"\"", "+ self.description ) def append_past_events(past_events, wiki_user, wiki_pw, wiki_archive): \"\"\" Append", "\"\"\" def __init__(self, event): \"\"\" :param event: The event to", "locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class EntropiaEvent: \"\"\" Parses an", "location = \" \" if self.event.location: location = self.event.location if", "@property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time :rtype:", "text is automatically generated by the ics2entropiawiki bot, everything you", "\" || \" + self.start_time + \" || \" +", ":return: A wiki line describing the event :rtype: str \"\"\"", "width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\" | Zeit", "list :param wiki_user: bot user for the wiki :type wiki_user:", "self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property", "locations.keys(): location = locations[location.lower()] return location @property def begin_date(self): \"\"\"", "\"[\"+links[0]+\" \"+event.name+\"]\" elif wiki: description = wiki[0] elif not event.name:", "+= \"\\n\"+line return deradicalised def main(): \"\"\" :return: None :rtype:", "the command line, the config file respectively :return: Parsed arguments", "from datetime import timedelta, datetime from ics import Calendar from", "BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch generiert.", "def is_past_event(self): \"\"\" :return: Check if the event lies in", "dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This text is", "'utf-8' calendar = Calendar(deradicalise_ical(ics_result.text)) for event in sorted(calendar.events, key=lambda ev:", "in locations.keys(): location = locations[location.lower()] return location @property def begin_date(self):", "entropia homepage wiki. Example: $ ics2entropiawiki.py --config /etc/ics2entropiawiki/config.ini Inserts events", "config file respectively :return: Parsed arguments from command line, config", "wiki_archive: str :return: None :rtype: None \"\"\" site = Site('entropia.de',", "metavar=\"FILE\" ) parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument(", "+ \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/') site.login(wiki['user'],", "= \"N.A.\" else: description = event.name return description def __str__(self):", ":rtype: list \"\"\" parser = ArgumentParser() parser.add_argument( \"-c\", \"--config\", default=\"/etc/ics2entropiawiki/config.ini\",", "\"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line:", "str :return: None :rtype: None \"\"\" site = Site('entropia.de', path='/')", "Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\"", "of an event :return: location :rtype: str \"\"\" locations =", "password\", metavar=\"WIKIPW\" ) parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' )", "argparse import ArgumentParser from datetime import timedelta, datetime from ics", "Zeit !! Ort !! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {|", "return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin", "python3 # -*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics", "you edit WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki", "configfile = args.configfile ics_url = args.ics_url file = args.local_file wiki", "return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self): \"\"\" :return: Entropia-Wiki formatted", "from command line, config file :rtype: list \"\"\" parser =", "( '\\n' + LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list,", "location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted begin time", "= parser.parse_args() configfile = args.configfile ics_url = args.ics_url file =", "self.endtime - self.begintime > timedelta(days=1): end_date = \" - \"", "!! Beschreibung\\ \"\"\" ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\"", "datetime import timedelta, datetime from ics import Calendar from mwclient", "return description def __str__(self): \"\"\" :return: A wiki line describing", "which the ICS-file can be retrieved\", metavar=\"URL\", ) parser.add_argument( \"-f\",", "dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive',", "parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args = parser.parse_args()", "ÜBERSCHRIEBEN --> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\"", "--config /etc/ics2entropiawiki/config.ini Inserts events not in the past to the", "def end_date(self): \"\"\" :return: Entropia-Wiki formatted end time :rtype: str", "+ \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\"", "\"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) + \"\\n\" +", "\"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\", dest=\"wiki_pw\", help=\"Wiki", "args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, } debug =", "event.begin.datetime.astimezone() self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the", "txtline in enumerate(text): if txtline == '|}': last_table_position = index", "wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER", "\" + self.start_time + \" || \" + self.location +", "cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" | Datum !! style=\"width:50px;\"", "re.findall(\"^[Ll]ink:(.*)$\", event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name:", "+ self.location + \" || \" + self.description ) def", "text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def get_args(): \"\"\" Retrieve arguments", "wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive':", "Parsed arguments from command line, config file :rtype: list \"\"\"", "= \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" !", "+ str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list =", "help=\"The URL under which the ICS-file can be retrieved\", metavar=\"URL\",", "end_date = \" - \" + self.endtime.strftime(\"%a., %d.%m.%Y\") return end_date", "= \"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if", "{ 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive, }", "= { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page, 'archive': args.wiki_archive,", "line: deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\" :return:", "--> \"\"\" TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\"", "event :return: location :rtype: str \"\"\" locations = { \"entropia\":", "and insert them in to the entropia homepage wiki. Example:", "by the ics2entropiawiki bot, everything you write and everything you", "automatisch generiert. Alles was hier manuell editiert, hinzugefügt wird WIRD", "the entropia events and insert them in to the entropia", "append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\" +", ":rtype: str \"\"\" return (\"| \" + self.begin_date + self.end_date", "= \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in", "the \"Vergangene_Termine\" Site \"\"\" import locale import configparser import re", "from mwclient import Site from dateutil.tz import tzlocal BOTWARNING =", "\"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki", "in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line", "parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\",", "ics_url, file, wiki, debug = get_args() event_strings = [] past_events", "= EntropiaEvent(event) if not event.is_past_event: event_strings.append( \"\\n\" + LINE_SEPARATOR +", "an event :return: location :rtype: str \"\"\" locations = {", "self.begintime > timedelta(days=1): end_date = \" - \" + self.endtime.strftime(\"%a.,", "\"\"\" links = None wiki = None event = self.event", "= None event = self.event if event.description: links = re.findall(\"^[Ll]ink:(.*)$\",", "\"== {} ==\".format(event.endtime.strftime('%Y')) for index, txtline in enumerate(text): if txtline", "the event :rtype: str \"\"\" return (\"| \" + self.begin_date", "year_header + ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' +", "Site from dateutil.tz import tzlocal BOTWARNING = \"\"\" <!-- This", "event: ics.event.Event \"\"\" self.event = event self.begintime = event.begin.datetime.astimezone() self.endtime", "ics_url, file, wiki, debug def deradicalise_ical(ics): \"\"\" :param ics: input", "key=lambda ev: ev.begin): event = EntropiaEvent(event) if not event.is_past_event: event_strings.append(", "str \"\"\" links = None wiki = None event =", "site = Site('entropia.de', path='/') site.login(wiki['user'], wiki['pass']) page = site.pages[wiki['page']] if", "of the event :rtype: str \"\"\" start_time = \" \"", "+ ARCHIVE_TABLE_HEADER + '\\n' + LINE_SEPARATOR + '\\n' + str(event)", ":return: Parsed arguments from command line, config file :rtype: list", "configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki = config[\"wiki\"] except", "if 'X-RADICALE-NAME:' not in line: deradicalised += \"\\n\"+line return deradicalised", ") parser.add_argument( \"--wiki-page\", dest=\"wiki_page\", help='Wiki page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\",", "input file :type ics: str :return: file with remove radicale_headers", "start_time = \" \" if not self.event.all_day: start_time = self.begintime.strftime(\"%H:%M\")", "if self.endtime - self.begintime > timedelta(days=1): end_date = \" -", "the past :rtype: bool \"\"\" return self.days_to_event < timedelta(days=0) @property", ") parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\",", "get_args() event_strings = [] past_events = [] if file: calendar", "in enumerate(text): if txtline == '|}': last_table_position = index if", "event.description) wiki = re.findall(\"^[Ww]iki:(.*)$\", event.description) if links and event.name: description", "\"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self): \"\"\" :return:", "locations[location.lower()] return location @property def begin_date(self): \"\"\" :return: Entropia-Wiki formatted", "wiki['archive']) termine = BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\"", "'page': args.wiki_page, 'archive': args.wiki_archive, } debug = args.debug if configfile:", "default=False ) args = parser.parse_args() configfile = args.configfile ics_url =", "the event lies in the past :rtype: bool \"\"\" return", "\"--url\", dest=\"ics_url\", help=\"The URL under which the ICS-file can be", ") text = text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3", "ARCHIVE_TABLE_HEADER = \"\"\" {| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" style=\"border-collapse:collapse;\" width=\"100%\"", "timedelta(days=0) @property def start_time(self): \"\"\" :return: The starting time of", "look at the sample config provided with the package\") raise", "default=\"/etc/ics2entropiawiki/config.ini\", dest=\"configfile\", help=\"Configuration file path\", metavar=\"CONFIG\" ) parser.add_argument( \"-u\", \"--url\",", "self.endtime = event._end_time.datetime.astimezone() @property def location(self): \"\"\" Retrieve the location", "past_events.append(event) append_past_events(past_events, wiki['user'], wiki['pass'], wiki['archive']) termine = BOTWARNING + \"\\n\"", "\"([https://entropia.de/index.php?title=Vorlage:Termine&action=edit Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\"", "wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n') last_table_position = 0", "in line: deradicalised += \"\\n\"+line return deradicalised def main(): \"\"\"", ":type wiki_pw: str :param wiki_archive: archive page :type wiki_archive: str", ") parser.add_argument( \"--wiki-user\", dest=\"wiki_user\", help=\"Wiki user\", metavar=\"WIKIUSER\" ) parser.add_argument( \"--wiki-password\",", "metavar='WIKIARCHIVE' ) parser.add_argument( \"-d\", \"--debug\", dest=\"debug\", action=\"store_true\", default=False ) args", "an ics file with the entropia events and insert them", "-*- coding: utf-8 -*- \"\"\"ics2entropiawiki Read an ics file with", "WILL BE OVERWRITTEN Dieser Text ist vom ics2entropiawiki bot automatisch", "if self.event.location: location = self.event.location if location.lower() in locations.keys(): location", "'\\n' + LINE_SEPARATOR + str(event) ) text = text[:last_table_position]+[append_list, ]+text[last_table_position:]", "the location of an event :return: location :rtype: str \"\"\"", "str(event) + '\\n|}' ) text = text[:last_table_position+1]+[append_list, ]+text[last_table_position+1:] page.save(\"\\n\".join(text)) def", "+ self.begin_date + self.end_date + \" || \" + self.start_time", "|width=15%|'''Datum''' |width=6%|'''Zeit''' |width=15%|'''Ort''' |width=69%|'''Beschreibung''' \"\"\" TABLE_FOOTER = ( \"|}\", \"\\n\",", "get_args(): \"\"\" Retrieve arguments from the command line, the config", "page', metavar='WIKIPAGE' ) parser.add_argument( \"--wiki-archive\", dest=\"wiki_archive\", help='Wiki archive', metavar='WIKIARCHIVE' )", "| Datum !! style=\"width:50px;\" | Zeit !! Ort !! Beschreibung\\", "deradicalised = \"\" for line in ics.splitlines(): if 'X-RADICALE-NAME:' not", "event to be evaluated :type event: ics.event.Event \"\"\" self.event =", "BOTWARNING + \"\\n\" + TABLE_HEADER + \"\\n\" + \"\".join(event_strings) +", "event in sorted(calendar.events, key=lambda ev: ev.begin): event = EntropiaEvent(event) if", "the sample config provided with the package\") raise error return", "page :type wiki_archive: str :return: None :rtype: None \"\"\" site", "file: calendar = Calendar(deradicalise_ical(open(file).read())) else: ics_result = requests.get(ics_url) ics_result.encoding =", "\"\\n\" + \"\".join(TABLE_FOOTER) if debug: print(termine) site = Site('entropia.de', path='/')", "description = wiki[0] elif not event.name: description = \"N.A.\" else:", "file :type ics: str :return: file with remove radicale_headers \"\"\"", "\"\"\" :param ics: input file :type ics: str :return: file", "= text[:last_table_position]+[append_list, ]+text[last_table_position:] else: append_list = ( 3 * '\\n'", ":return: Entropia-Wiki formatted end time :rtype: str \"\"\" end_date =", "Site('entropia.de', path='/') site.login(wiki_user, wiki_pw) page = site.pages[wiki_archive] text = page.text().split('\\n')", "locale.Error: pass class EntropiaEvent: \"\"\" Parses an ics Event and", "def __str__(self): \"\"\" :return: A wiki line describing the event", "\"\"\" Retrieve the location of an event :return: location :rtype:", "text = page.text().split('\\n') last_table_position = 0 for event in past_events:", ":return: Check if the event lies in the past :rtype:", "{| class=\"termine\" border=\"1\" cellspacing=\"0\" cellpadding=\"5\" width=\"100%\" style=\"border-collapse:collapse;\" ! style=\"width:250px;\" |", ":rtype: datetime.timedelta \"\"\" return self.endtime - datetime.now(tz=tzlocal()) @property def is_past_event(self):", "for line in ics.splitlines(): if 'X-RADICALE-NAME:' not in line: deradicalised", "configfile: config = configparser.ConfigParser() config.read(configfile) try: ics_url = config[\"default\"][\"url\"] wiki", "= args.ics_url file = args.local_file wiki = { 'user': args.wiki_user,", "in text: append_list = ( '\\n' + LINE_SEPARATOR + str(event)", "args.local_file wiki = { 'user': args.wiki_user, 'pass': args.wiki_pw, 'page': args.wiki_page,", "ics: str :return: file with remove radicale_headers \"\"\" deradicalised =", "Bearbeiten]),\", \" [[Vorlage:Vergangene_Termine|Vergangene Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try:", "LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except locale.Error: pass class", "Termine]], [[Anfahrt]]\" ) LINE_SEPARATOR = \"|-\\n\" try: locale.setlocale(locale.LC_ALL, 'de_DE.utf8') except", "\" + self.begin_date + self.end_date + \" || \" +", "time :rtype: str \"\"\" return self.begintime.strftime(\"%a., %d.%m.%Y\") @property def end_date(self):", "to the events page :type past_events: list :param wiki_user: bot", "self.begin_date + self.end_date + \" || \" + self.start_time +" ]
[ "= list(a) b = alist[d:]+alist[:d] return b if __name__ ==", "sys # Complete the rotLeft function below. def rotLeft(a, d):", "list(a) b = alist[d:]+alist[:d] return b if __name__ == '__main__':", "import random import re import sys # Complete the rotLeft", "= int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result", "= int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d)", "rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return b", "import re import sys # Complete the rotLeft function below.", "Complete the rotLeft function below. def rotLeft(a, d): alist =", "def rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d] return", "#!/bin/python3 import math import os import random import re import", "function below. def rotLeft(a, d): alist = list(a) b =", "d): alist = list(a) b = alist[d:]+alist[:d] return b if", "# Complete the rotLeft function below. def rotLeft(a, d): alist", "b = alist[d:]+alist[:d] return b if __name__ == '__main__': fptr", "alist = list(a) b = alist[d:]+alist[:d] return b if __name__", "__name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split()", "= open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0]) d", "math import os import random import re import sys #", "fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0])", "input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str, result))) fptr.write('\\n') fptr.close()", "a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str,", "return b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w')", "rotLeft function below. def rotLeft(a, d): alist = list(a) b", "int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write('", "= list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str, result)))", "random import re import sys # Complete the rotLeft function", "below. def rotLeft(a, d): alist = list(a) b = alist[d:]+alist[:d]", "import sys # Complete the rotLeft function below. def rotLeft(a,", "= input().split() n = int(nd[0]) d = int(nd[1]) a =", "alist[d:]+alist[:d] return b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'],", "input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int,", "os import random import re import sys # Complete the", "import math import os import random import re import sys", "n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split()))", "open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n = int(nd[0]) d =", "'w') nd = input().split() n = int(nd[0]) d = int(nd[1])", "'__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n =", "import os import random import re import sys # Complete", "if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd =", "the rotLeft function below. def rotLeft(a, d): alist = list(a)", "= alist[d:]+alist[:d] return b if __name__ == '__main__': fptr =", "d = int(nd[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a,", "b if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd", "re import sys # Complete the rotLeft function below. def", "nd = input().split() n = int(nd[0]) d = int(nd[1]) a", "int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) result =", "== '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nd = input().split() n", "list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str, result))) fptr.write('\\n')" ]
[ "cflearn import platform import unittest from cfdata.tabular import TabularDataset num_jobs", "= \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None:", "y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self)", "-> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__", "key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] =", "zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m =", "key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x,", "import TabularDataset num_jobs = 0 if platform.system() == \"Linux\" else", "pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) ->", "0 if platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\"", "zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder =", "@staticmethod def _test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy", "f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder", "= cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder,", "cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None:", "_test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy zoo_folder =", "x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo =", "local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder)", "import platform import unittest from cfdata.tabular import TabularDataset num_jobs =", "y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\")", "TabularDataset num_jobs = 0 if platform.system() == \"Linux\" else 2", "TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key,", "-> None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\")", "cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) ->", "platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase):", "def _test_zoo_core(model: str) -> None: x, y = TabularDataset.iris().xy zoo_folder", "from cfdata.tabular import TabularDataset num_jobs = 0 if platform.system() ==", "def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__ == \"__main__\": unittest.main()", "\"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def", "def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\")", "cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def", "else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model:", "os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y)", "for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"]", "None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo", "os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in zoo.benchmarks.items():", "unittest from cfdata.tabular import TabularDataset num_jobs = 0 if platform.system()", "2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str)", "in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m", "= cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self)", "if platform.system() == \"Linux\" else 2 logging_folder = \"__test_zoo__\" class", "None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__ ==", "str) -> None: x, y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder,", "y = TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model)", "num_jobs = 0 if platform.system() == \"Linux\" else 2 logging_folder", "\"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x,", "config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder", "= TabularDataset.iris().xy zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for", "import cflearn import platform import unittest from cfdata.tabular import TabularDataset", "local_logging_folder = os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model,", "== \"Linux\" else 2 logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod", "= 0 if platform.system() == \"Linux\" else 2 logging_folder =", "import os import cflearn import platform import unittest from cfdata.tabular", "= os.path.join(zoo_folder, key) config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x,", "class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x, y", "zoo_folder = os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config", "= os.path.join(logging_folder, f\"__{model}__\") zoo = cflearn.Zoo(model) for key, config in", "TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) -> None: x, y =", "m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def", "self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if __name__ == \"__main__\":", "cfdata.tabular import TabularDataset num_jobs = 0 if platform.system() == \"Linux\"", "cflearn.Zoo(model) for key, config in zoo.benchmarks.items(): local_logging_folder = os.path.join(zoo_folder, key)", "config[\"logging_folder\"] = local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y,", "= local_logging_folder m = cflearn.make(model, **config).fit(x, y) cflearn.evaluate(x, y, pipelines=m)", "os import cflearn import platform import unittest from cfdata.tabular import", "import unittest from cfdata.tabular import TabularDataset num_jobs = 0 if", "**config).fit(x, y) cflearn.evaluate(x, y, pipelines=m) cflearn._rmtree(logging_folder) def test_fcnn_zoo(self) -> None:", "test_fcnn_zoo(self) -> None: self._test_zoo_core(\"fcnn\") def test_tree_dnn_zoo(self) -> None: self._test_zoo_core(\"tree_dnn\") if", "platform import unittest from cfdata.tabular import TabularDataset num_jobs = 0", "logging_folder = \"__test_zoo__\" class TestZoo(unittest.TestCase): @staticmethod def _test_zoo_core(model: str) ->" ]
[ "right.head # Iterate over left and right until we reach", "the tail node from left to merged linked list elif", "left to set loop condition to False left_head = left_head.next_node", "current to left node if left_data < right_data: current.next_node =", "if linked_list == None or linked_list.head == None: left_half =", "from right to merged linkned list if left_head is None:", "mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half", "left head to next node left_head = left_head.next_node # If", "= left_head # Call next on left to set loop", "data in nodes. Returns a new, merged list. Runs in", "loop condition to False left_head = left_head.next_node else: # Not", "linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked", "None: current.next_node = right_head # Call next on right to", "right node else: current.next_node = right_head # Move right head", "by <NAME> on 3/24/19. # Copyright (c) 2019 ddApps. All", "the tail # Add the tail node from left to", "two linked lists, sorting by data in nodes. Returns a", "import Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked list", "head to next node left_head = left_head.next_node # If data", "# # Created by <NAME> on 3/24/19. # Copyright (c)", "LinkedList def merge_sort(linked_list): ''' Sorts a linked list in ascending", "None: left_half = linked_list right_half = None return left_half, right_half", "node # of either while left_head or right_head: # If", "produce sorted swublists until one remains Returns a sorted linked", "def merge_sort(linked_list): ''' Sorts a linked list in ascending order.", "linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node = None", "if linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return linked_list", "left_half, right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half)", "= left_head.next_node else: # Not at either tail node #", "linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right =", "later to simplify code merged.add(0) # Set current to the", "the midpoint into sublists. Takes O(k log n) quasilinear time.", "of right is None, we're past the tail # Add", "until one remains Returns a sorted linked list. Runs in", "list. Runs in O(kn log n) time. ''' if linked_list.size()", "Create a new linked list that contains nodes from #", "Merge Sort: The Conquer Step # Python Techdegree # #", "left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def", "either while left_head or right_head: # If the head node", "first merged node as head head = merged.head.next_node merged.head =", "Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ from", "list into sublists containing a single node - Repeatedly merge", "head to next node right_head = right_head.next_node # Move current", "right_half def merge(left, right): ''' Merges two linked lists, sorting", "left_head or right_head: # If the head node of the", "''' Divide the unsorted list at the midpoint into sublists.", "of the left is None, we're past the tail #", "fake head that is discarded later to simplify code merged.add(0)", "Recuresively divide the linked list into sublists containing a single", "Add the tail node from left to merged linked list", "node as head head = merged.head.next_node merged.head = head return", "right_head # Move right head to next node right_head =", "current to next node current = current.next_node # Discard fake", "# Obtain head nodes for left and right linked lists", "right to merged linkned list if left_head is None: current.next_node", "at either tail node # Obtain node data to perform", "left is less than right, set current to left node", "of either while left_head or right_head: # If the head", "from left to merged linked list elif right_head is None:", "split(linked_list): ''' Divide the unsorted list at the midpoint into", "left and right linked lists left_head = left.head right_head =", "and right merged = LinkedList() # Add a fake head", "# If data on left is less than right, set", "sublists containing a single node - Repeatedly merge the sublists", "merged node as head head = merged.head.next_node merged.head = head", "merging left and right merged = LinkedList() # Add a", "reserved. # ------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list):", "sublists to produce sorted swublists until one remains Returns a", "log n) time. ''' if linked_list.size() == 1: return linked_list", "linked lists, sorting by data in nodes. Returns a new,", "either tail node # Obtain node data to perform comparison", "one remains Returns a sorted linked list. Runs in O(kn", "linked list in ascending order. - Recuresively divide the linked", "is less than right, set current to left node if", "the tail # Add the node from right to merged", "the linked list current = merged.head # Obtain head nodes", "Takes O(k log n) quasilinear time. ''' if linked_list ==", "merged.head = head return merged l = LinkedList() l.add(10) l.add(2)", "set loop condition to False left_head = left_head.next_node else: #", "the left is None, we're past the tail # Add", "''' if linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return", "else: # Not at either tail node # Obtain node", "midpoint into sublists. Takes O(k log n) quasilinear time. '''", "# Data Structures: Linked List Merge Sort: The Conquer Step", "merged.add(0) # Set current to the head of the linked", "# If data on left is greater than right, set", "a linked list in ascending order. - Recuresively divide the", "merged.head.next_node merged.head = head return merged l = LinkedList() l.add(10)", "left and right until we reach the tail node #", "left node if left_data < right_data: current.next_node = left_head #", "= left_head.next_node # If data on left is greater than", "Not at either tail node # Obtain node data to", "Linked List Merge Sort: The Conquer Step # Python Techdegree", "right_data: current.next_node = left_head # Move left head to next", "into sublists containing a single node - Repeatedly merge the", "a sorted linked list. Runs in O(kn log n) time.", "Move current to next node current = current.next_node # Discard", "past the tail # Add the node from right to", "of the linked list current = merged.head # Obtain head", "the linked list into sublists containing a single node -", "merged list. Runs in O(n) linear time. ''' # Create", "lists, sorting by data in nodes. Returns a new, merged", "merge(left, right) def split(linked_list): ''' Divide the unsorted list at", "we're past the tail # Add the node from right", "Move left head to next node left_head = left_head.next_node #", "on left is greater than right, set current to right", "LinkedList() right_half = mid_node.next_node mid_node.next_node = None return left_half, right_half", "is discarded later to simplify code merged.add(0) # Set current", "than right, set current to left node if left_data <", "nodes. Returns a new, merged list. Runs in O(n) linear", "merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list): '''", "current = merged.head # Obtain head nodes for left and", "the sublists to produce sorted swublists until one remains Returns", "== None or linked_list.head == None: left_half = linked_list right_half", "linked list that contains nodes from # merging left and", "= linked_list.size() midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1)", "# Move current to next node current = current.next_node #", "as head head = merged.head.next_node merged.head = head return merged", "Obtain head nodes for left and right linked lists left_head", "and right until we reach the tail node # of", "next on left to set loop condition to False left_head", "left_head = left.head right_head = right.head # Iterate over left", "data to perform comparison operations left_data = left_head.data right_data =", "next node right_head = right_head.next_node # Move current to next", "quasilinear time. ''' if linked_list == None or linked_list.head ==", "tail node # of either while left_head or right_head: #", "linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half)", "else: # non-empty linked lists size = linked_list.size() midpoint =", "while left_head or right_head: # If the head node of", "node of the left is None, we're past the tail", "linked list into sublists containing a single node - Repeatedly", "# Obtain node data to perform comparison operations left_data =", "on left is less than right, set current to left", "sorting by data in nodes. Returns a new, merged list.", "Add a fake head that is discarded later to simplify", "# Iterate over left and right until we reach the", "If data on left is less than right, set current", "list at the midpoint into sublists. Takes O(k log n)", "= None return left_half, right_half else: # non-empty linked lists", "Merges two linked lists, sorting by data in nodes. Returns", "Runs in O(n) linear time. ''' # Create a new", "and right linked lists left_head = left.head right_head = right.head", "new linked list that contains nodes from # merging left", "size = linked_list.size() midpoint = size // 2 mid_node =", "right) def split(linked_list): ''' Divide the unsorted list at the", "- Recuresively divide the linked list into sublists containing a", "we reach the tail node # of either while left_head", "if left_data < right_data: current.next_node = left_head # Move left", "head of the linked list current = merged.head # Obtain", "current.next_node = left_head # Move left head to next node", "# Add a fake head that is discarded later to", "LinkedList() # Add a fake head that is discarded later", "right to set loop condition to False right_head = right_head.next_node", "mid_node.next_node = None return left_half, right_half def merge(left, right): '''", "# Add the tail node from left to merged linked", "to left node if left_data < right_data: current.next_node = left_head", "linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half = mid_node.next_node", "swublists until one remains Returns a sorted linked list. Runs", "# # Data Structures: Linked List Merge Sort: The Conquer", "to merged linked list elif right_head is None: current.next_node =", "Step # Python Techdegree # # Created by <NAME> on", "non-empty linked lists size = linked_list.size() midpoint = size //", "merged.head # Obtain head nodes for left and right linked", "False right_head = right_head.next_node # If the head node of", "right linked lists left_head = left.head right_head = right.head #", "right = merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide", "# Not at either tail node # Obtain node data", "= LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list =", "right_head.next_node # Move current to next node current = current.next_node", "The Conquer Step # Python Techdegree # # Created by", "= left_head # Move left head to next node left_head", "left_half, right_half else: # non-empty linked lists size = linked_list.size()", "left_head = left_head.next_node else: # Not at either tail node", "comparison operations left_data = left_head.data right_data = right_head.data # If", "linked_list.head == None: left_half = linked_list right_half = None return", "we're past the tail # Add the tail node from", "is greater than right, set current to right node else:", "left_half, right_half def merge(left, right): ''' Merges two linked lists,", "node right_head = right_head.next_node # Move current to next node", "right_half else: # non-empty linked lists size = linked_list.size() midpoint", "= right_head # Move right head to next node right_head", "on 3/24/19. # Copyright (c) 2019 ddApps. All rights reserved.", "the tail node # of either while left_head or right_head:", "to False right_head = right_head.next_node # If the head node", "# If the head node of the left is None,", "next on right to set loop condition to False right_head", "Repeatedly merge the sublists to produce sorted swublists until one", "to perform comparison operations left_data = left_head.data right_data = right_head.data", "== 1: return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half", "node data to perform comparison operations left_data = left_head.data right_data", "left_head.data right_data = right_head.data # If data on left is", "tail node # Obtain node data to perform comparison operations", "next node left_head = left_head.next_node # If data on left", "n) time. ''' if linked_list.size() == 1: return linked_list elif", "left is None, we're past the tail # Add the", "linked_list.size() == 1: return linked_list elif linked_list.is_empty(): return linked_list left_half,", "tail node from left to merged linked list elif right_head", "= merged.head.next_node merged.head = head return merged l = LinkedList()", "O(kn log n) time. ''' if linked_list.size() == 1: return", "# Call next on right to set loop condition to", "new, merged list. Runs in O(n) linear time. ''' #", "right_half = split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return", "Returns a new, merged list. Runs in O(n) linear time.", "a new linked list that contains nodes from # merging", "at the midpoint into sublists. Takes O(k log n) quasilinear", "Conquer Step # Python Techdegree # # Created by <NAME>", "node if left_data < right_data: current.next_node = left_head # Move", "= left_head.data right_data = right_head.data # If data on left", "lists left_head = left.head right_head = right.head # Iterate over", "set first merged node as head head = merged.head.next_node merged.head", "left.head right_head = right.head # Iterate over left and right", "2019 ddApps. All rights reserved. # ------------------------------------------------ from linked_list import", "to simplify code merged.add(0) # Set current to the head", "right_head: # If the head node of the left is", "contains nodes from # merging left and right merged =", "current.next_node # Discard fake head and set first merged node", "''' Sorts a linked list in ascending order. - Recuresively", "= right_head.next_node # Move current to next node current =", "Sorts a linked list in ascending order. - Recuresively divide", "head head = merged.head.next_node merged.head = head return merged l", "# of either while left_head or right_head: # If the", "current.next_node = left_head # Call next on left to set", "until we reach the tail node # of either while", "on right to set loop condition to False right_head =", "the head node of right is None, we're past the", "Set current to the head of the linked list current", "= right.head # Iterate over left and right until we", "left to merged linked list elif right_head is None: current.next_node", "right, set current to right node else: current.next_node = right_head", "// 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half =", "Divide the unsorted list at the midpoint into sublists. Takes", "current to the head of the linked list current =", "to merged linkned list if left_head is None: current.next_node =", "# If the head node of right is None, we're", "Move right head to next node right_head = right_head.next_node #", "def split(linked_list): ''' Divide the unsorted list at the midpoint", "linked lists left_head = left.head right_head = right.head # Iterate", "right_head = right.head # Iterate over left and right until", "the head node of the left is None, we're past", "= merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide the", "If the head node of the left is None, we're", "If the head node of right is None, we're past", "sublists. Takes O(k log n) quasilinear time. ''' if linked_list", "on left to set loop condition to False left_head =", "set loop condition to False right_head = right_head.next_node # If", "2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList()", "list. Runs in O(n) linear time. ''' # Create a", "merge(left, right): ''' Merges two linked lists, sorting by data", "rights reserved. # ------------------------------------------------ from linked_list import Node, LinkedList def", "list that contains nodes from # merging left and right", "linear time. ''' # Create a new linked list that", "log n) quasilinear time. ''' if linked_list == None or", "left_head.next_node # If data on left is greater than right,", "Techdegree # # Created by <NAME> on 3/24/19. # Copyright", "ddApps. All rights reserved. # ------------------------------------------------ from linked_list import Node,", "= linked_list right_half = None return left_half, right_half else: #", "left and right merged = LinkedList() # Add a fake", "= linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node =", "head that is discarded later to simplify code merged.add(0) #", "nodes from # merging left and right merged = LinkedList()", "right_data = right_head.data # If data on left is less", "that contains nodes from # merging left and right merged", "remains Returns a sorted linked list. Runs in O(kn log", "------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts", "= LinkedList() right_half = mid_node.next_node mid_node.next_node = None return left_half,", "left_data < right_data: current.next_node = left_head # Move left head", "or linked_list.head == None: left_half = linked_list right_half = None", "''' if linked_list == None or linked_list.head == None: left_half", "def merge(left, right): ''' Merges two linked lists, sorting by", "O(n) linear time. ''' # Create a new linked list", "merged = LinkedList() # Add a fake head that is", "None or linked_list.head == None: left_half = linked_list right_half =", "time. ''' # Create a new linked list that contains", "split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left, right)", "for left and right linked lists left_head = left.head right_head", "sorted swublists until one remains Returns a sorted linked list.", "# non-empty linked lists size = linked_list.size() midpoint = size", "current = current.next_node # Discard fake head and set first", "LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list = merge_sort(l)", "linkned list if left_head is None: current.next_node = right_head #", "<gh_stars>10-100 # # Data Structures: Linked List Merge Sort: The", "fake head and set first merged node as head head", "from # merging left and right merged = LinkedList() #", "= head return merged l = LinkedList() l.add(10) l.add(2) l.add(44)", "right_head.next_node # If the head node of right is None,", "code merged.add(0) # Set current to the head of the", "list in ascending order. - Recuresively divide the linked list", "to False left_head = left_head.next_node else: # Not at either", "merged linkned list if left_head is None: current.next_node = right_head", "node from right to merged linkned list if left_head is", "Sort: The Conquer Step # Python Techdegree # # Created", "# Move right head to next node right_head = right_head.next_node", "loop condition to False right_head = right_head.next_node # If the", "O(k log n) quasilinear time. ''' if linked_list == None", "''' # Create a new linked list that contains nodes", "a new, merged list. Runs in O(n) linear time. '''", "nodes for left and right linked lists left_head = left.head", "return merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200)", "= size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list", "= left.head right_head = right.head # Iterate over left and", "right_head = right_head.next_node # Move current to next node current", "Runs in O(kn log n) time. ''' if linked_list.size() ==", "the node from right to merged linkned list if left_head", "- Repeatedly merge the sublists to produce sorted swublists until", "Returns a sorted linked list. Runs in O(kn log n)", "left_head # Move left head to next node left_head =", "If data on left is greater than right, set current", "= split(linked_list) left = merge_sort(left_half) right = merge_sort(right_half) return merge(left,", "node # Obtain node data to perform comparison operations left_data", "node else: current.next_node = right_head # Move right head to", "size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half = linked_list right_half", "sorted linked list. Runs in O(kn log n) time. '''", "# Created by <NAME> on 3/24/19. # Copyright (c) 2019", "All rights reserved. # ------------------------------------------------ from linked_list import Node, LinkedList", "Call next on left to set loop condition to False", "= merged.head # Obtain head nodes for left and right", "return left_half, right_half def merge(left, right): ''' Merges two linked", "right, set current to left node if left_data < right_data:", "linked_list right_half = None return left_half, right_half else: # non-empty", "linked list elif right_head is None: current.next_node = left_head #", "elif right_head is None: current.next_node = left_head # Call next", "past the tail # Add the tail node from left", "right merged = LinkedList() # Add a fake head that", "# Call next on left to set loop condition to", "right is None, we're past the tail # Add the", "right_head is None: current.next_node = left_head # Call next on", "right_half = None return left_half, right_half else: # non-empty linked", "= right_head # Call next on right to set loop", "return left_half, right_half else: # non-empty linked lists size =", "Obtain node data to perform comparison operations left_data = left_head.data", "discarded later to simplify code merged.add(0) # Set current to", "False left_head = left_head.next_node else: # Not at either tail", "is None, we're past the tail # Add the tail", "containing a single node - Repeatedly merge the sublists to", "midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half =", "order. - Recuresively divide the linked list into sublists containing", "to produce sorted swublists until one remains Returns a sorted", "else: current.next_node = right_head # Move right head to next", "left_half = linked_list right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node", "list elif right_head is None: current.next_node = left_head # Call", "to set loop condition to False right_head = right_head.next_node #", "to next node right_head = right_head.next_node # Move current to", "return linked_list left_half, right_half = split(linked_list) left = merge_sort(left_half) right", "the head of the linked list current = merged.head #", "merge the sublists to produce sorted swublists until one remains", "merged linked list elif right_head is None: current.next_node = left_head", "left_head = left_head.next_node # If data on left is greater", "mid_node.next_node mid_node.next_node = None return left_half, right_half def merge(left, right):", "set current to right node else: current.next_node = right_head #", "in ascending order. - Recuresively divide the linked list into", "operations left_data = left_head.data right_data = right_head.data # If data", "data on left is less than right, set current to", "# Create a new linked list that contains nodes from", "than right, set current to right node else: current.next_node =", "Node, LinkedList def merge_sort(linked_list): ''' Sorts a linked list in", "divide the linked list into sublists containing a single node", "linked_list elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left", "ascending order. - Recuresively divide the linked list into sublists", "< right_data: current.next_node = left_head # Move left head to", "= LinkedList() # Add a fake head that is discarded", "head node of right is None, we're past the tail", "return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list)", "tail # Add the node from right to merged linkned", "set current to left node if left_data < right_data: current.next_node", "left_half = linked_list right_half = None return left_half, right_half else:", "left_head.next_node else: # Not at either tail node # Obtain", "# Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------", "if left_head is None: current.next_node = right_head # Call next", "right_half = mid_node.next_node mid_node.next_node = None return left_half, right_half def", "that is discarded later to simplify code merged.add(0) # Set", "3/24/19. # Copyright (c) 2019 ddApps. All rights reserved. #", "None return left_half, right_half def merge(left, right): ''' Merges two", "current.next_node = right_head # Call next on right to set", "to set loop condition to False left_head = left_head.next_node else:", "''' Merges two linked lists, sorting by data in nodes.", "(c) 2019 ddApps. All rights reserved. # ------------------------------------------------ from linked_list", "l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list", "Iterate over left and right until we reach the tail", "= right_head.next_node # If the head node of right is", "in O(kn log n) time. ''' if linked_list.size() == 1:", "greater than right, set current to right node else: current.next_node", "None return left_half, right_half else: # non-empty linked lists size", "lists size = linked_list.size() midpoint = size // 2 mid_node", "# Move left head to next node left_head = left_head.next_node", "node - Repeatedly merge the sublists to produce sorted swublists", "# Discard fake head and set first merged node as", "n) quasilinear time. ''' if linked_list == None or linked_list.head", "head return merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15)", "merged l = LinkedList() l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l)", "tail # Add the tail node from left to merged", "left_head # Call next on left to set loop condition", "Discard fake head and set first merged node as head", "node current = current.next_node # Discard fake head and set", "perform comparison operations left_data = left_head.data right_data = right_head.data #", "= current.next_node # Discard fake head and set first merged", "unsorted list at the midpoint into sublists. Takes O(k log", "into sublists. Takes O(k log n) quasilinear time. ''' if", "right_head = right_head.next_node # If the head node of right", "next node current = current.next_node # Discard fake head and", "Data Structures: Linked List Merge Sort: The Conquer Step #", "linked list current = merged.head # Obtain head nodes for", "l.add(10) l.add(2) l.add(44) l.add(15) l.add(200) print(l) sorted_linked_list = merge_sort(l) print(sorted_linked_list)", "right until we reach the tail node # of either", "= right_head.data # If data on left is less than", "right_head.data # If data on left is less than right,", "time. ''' if linked_list == None or linked_list.head == None:", "right): ''' Merges two linked lists, sorting by data in", "linked list. Runs in O(kn log n) time. ''' if", "by data in nodes. Returns a new, merged list. Runs", "the unsorted list at the midpoint into sublists. Takes O(k", "1: return linked_list elif linked_list.is_empty(): return linked_list left_half, right_half =", "right_half = LinkedList() right_half = mid_node.next_node mid_node.next_node = None return", "in nodes. Returns a new, merged list. Runs in O(n)", "a single node - Repeatedly merge the sublists to produce", "right head to next node right_head = right_head.next_node # Move", "return merge(left, right) def split(linked_list): ''' Divide the unsorted list", "in O(n) linear time. ''' # Create a new linked", "= merge_sort(left_half) right = merge_sort(right_half) return merge(left, right) def split(linked_list):", "# ------------------------------------------------ from linked_list import Node, LinkedList def merge_sort(linked_list): '''", "less than right, set current to left node if left_data", "or right_head: # If the head node of the left", "merge_sort(linked_list): ''' Sorts a linked list in ascending order. -", "linked lists size = linked_list.size() midpoint = size // 2", "left_data = left_head.data right_data = right_head.data # If data on", "node from left to merged linked list elif right_head is", "= None return left_half, right_half def merge(left, right): ''' Merges", "# Set current to the head of the linked list", "data on left is greater than right, set current to", "None: current.next_node = left_head # Call next on left to", "# merging left and right merged = LinkedList() # Add", "Add the node from right to merged linkned list if", "to next node left_head = left_head.next_node # If data on", "# Python Techdegree # # Created by <NAME> on 3/24/19.", "left is greater than right, set current to right node", "merge_sort(right_half) return merge(left, right) def split(linked_list): ''' Divide the unsorted", "is None: current.next_node = left_head # Call next on left", "elif linked_list.is_empty(): return linked_list left_half, right_half = split(linked_list) left =", "= linked_list.node_at_index(midpoint-1) left_half = linked_list right_half = LinkedList() right_half =", "a fake head that is discarded later to simplify code", "is None, we're past the tail # Add the node", "list if left_head is None: current.next_node = right_head # Call", "to right node else: current.next_node = right_head # Move right", "node left_head = left_head.next_node # If data on left is", "node of right is None, we're past the tail #", "head = merged.head.next_node merged.head = head return merged l =", "linked_list.size() midpoint = size // 2 mid_node = linked_list.node_at_index(midpoint-1) left_half", "head node of the left is None, we're past the", "head nodes for left and right linked lists left_head =", "is None: current.next_node = right_head # Call next on right", "None, we're past the tail # Add the tail node", "condition to False right_head = right_head.next_node # If the head", "= mid_node.next_node mid_node.next_node = None return left_half, right_half def merge(left,", "to the head of the linked list current = merged.head", "Structures: Linked List Merge Sort: The Conquer Step # Python", "current to right node else: current.next_node = right_head # Move", "to next node current = current.next_node # Discard fake head", "current.next_node = right_head # Move right head to next node", "over left and right until we reach the tail node", "linked_list == None or linked_list.head == None: left_half = linked_list", "left_head is None: current.next_node = right_head # Call next on", "list current = merged.head # Obtain head nodes for left", "head and set first merged node as head head =", "<NAME> on 3/24/19. # Copyright (c) 2019 ddApps. All rights", "single node - Repeatedly merge the sublists to produce sorted", "condition to False left_head = left_head.next_node else: # Not at", "from linked_list import Node, LinkedList def merge_sort(linked_list): ''' Sorts a", "# Add the node from right to merged linkned list", "Python Techdegree # # Created by <NAME> on 3/24/19. #", "Call next on right to set loop condition to False", "List Merge Sort: The Conquer Step # Python Techdegree #", "Created by <NAME> on 3/24/19. # Copyright (c) 2019 ddApps.", "== None: left_half = linked_list right_half = None return left_half,", "simplify code merged.add(0) # Set current to the head of", "None, we're past the tail # Add the node from", "right_head # Call next on right to set loop condition", "time. ''' if linked_list.size() == 1: return linked_list elif linked_list.is_empty():", "and set first merged node as head head = merged.head.next_node", "reach the tail node # of either while left_head or" ]
[ "# Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm,", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10])", "HashPermutationMapper('permut2') # Create binary hash as child hash rbp_perm2 =", "(t1-t0)) # Get random query vector query = numpy.random.randn(DIM) #", "distance=CosineDistance()) # First index some random vectors matrix = numpy.zeros((POINTS,DIM))", "# Create binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm',", "print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query)", "# Do random query on engine 3 print('\\nNeighbour distances with", "with multiple binary hashes...') t0 = time.time() hashes = []", "binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) #", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "HashPermutationMapper:') print(' -> Candidate count is %d' % engine_perm2.candidate_count(query)) results", "-> Candidate count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query)", "rights # to use, copy, modify, merge, publish, distribute, sublicense,", "permission notice shall be included in # all copies or", "engine_perm.neighbours(query) dists = [x[2] for x in results] print(dists) #", "= HashPermutations('permut') # Create binary hash as child hash rbp_perm", "DIM = 100 # Number of data points (dont do", "from nearpy import Engine from nearpy.distances import CosineDistance from nearpy.hashes", "v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time()", "dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple", "permutations meta-hash permutations = HashPermutations('permut') # Create binary hash as", "multiple binary hashes...') t0 = time.time() hashes = [] for", "much because of exact search) POINTS = 20000 ########################################################## print('Performing", "Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors matrix", "4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count is", "100 # Number of data points (dont do too much", "i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v)", "= sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...')", "and associated documentation files (the \"Software\"), to deal # in", "Software without restriction, including without limitation the rights # to", "HashPermutations, HashPermutationMapper def example2(): # Dimension of feature space DIM", "and to permit persons to whom the Software is #", "copies of the Software, and to permit persons to whom", "hereby granted, free of charge, to any person obtaining a", "space DIM = 100 # Number of data points (dont", "vector query = numpy.random.randn(DIM) # Do random query on engine", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "distribute, sublicense, and/or sell # copies of the Software, and", "Then update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took", "= [x[2] for x in results] print(dists) # Real neighbours", "as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100}", "Candidate count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists", "# all copies or substantial portions of the Software. #", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists)", "HashPermutations:') print(' -> Candidate count is %d' % engine_perm.candidate_count(query)) results", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "included in # all copies or substantial portions of the", "= time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') #", "for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v", "results] print(dists) # Real neighbours print('\\nReal neighbour distances:') query =", "range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 =", "OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH", "[x[2] for x in results] print(dists) # Real neighbours print('\\nReal", "k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance())", "deal # in the Software without restriction, including without limitation", "Create permutations meta-hash permutations = HashPermutations('permut') # Create binary hash", "CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): #", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell #", "v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds' %", "notice and this permission notice shall be included in #", "%d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for", "RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash of permutations", "= numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour", "Dimension of feature space DIM = 100 # Number of", "copy, modify, merge, publish, distribute, sublicense, and/or sell # copies", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "time from nearpy import Engine from nearpy.distances import CosineDistance from", "rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) #", "random query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print('", "hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance())", "with HashPermutations:') print(' -> Candidate count is %d' % engine_perm.candidate_count(query))", "Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index", "in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1", "as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create", "time.time() print('Indexing took %f seconds' % (t1-t0)) # Get random", "Do random query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:')", "print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0 =", "data points (dont do too much because of exact search)", "software and associated documentation files (the \"Software\"), to deal #", "OR OTHER DEALINGS IN # THE SOFTWARE. import numpy import", "= query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps = Engine(DIM,", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR", "of exact search) POINTS = 20000 ########################################################## print('Performing indexing with", "the Software without restriction, including without limitation the rights #", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper", "time.time() hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' %", "%f seconds' % (t1-t0)) # Get random query vector query", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps =", "index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i in", "Copyright (c) 2013 <NAME> # Permission is hereby granted, free", "in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1", "print(' -> Candidate count is %d' % engine_rbps.candidate_count(query)) results =", "hashes...') t0 = time.time() hashes = [] for k in", "with HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash permutations2", "of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm =", "= engine_perm.neighbours(query) dists = [x[2] for x in results] print(dists)", "# of this software and associated documentation files (the \"Software\"),", "furnished to do so, subject to the following conditions: #", "# The above copyright notice and this permission notice shall", "SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "= v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds'", "indexing with multiple binary hashes...') t0 = time.time() hashes =", "a copy # of this software and associated documentation files", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF", "= dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with", "print('\\nPerforming indexing with multiple binary hashes...') t0 = time.time() hashes", "notice shall be included in # all copies or substantial", "in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine engine_rbps", "= time.time() hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d'", "results = engine_perm2.neighbours(query) dists = [x[2] for x in results]", "child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as", "THE SOFTWARE. import numpy import scipy import unittest import time", "= RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash of", "neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "and this permission notice shall be included in # all", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "import scipy import unittest import time from nearpy import Engine", "NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE", "seconds' % (t1-t0)) # Get random query vector query =", "to deal # in the Software without restriction, including without", "permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2],", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0", "IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS", "range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then", "Do random query on engine 4 print('\\nNeighbour distances with multiple", "# Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First", "% engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for x", "t0 = time.time() # Create permutations meta-hash permutations = HashPermutations('permut')", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash", "random query on engine 4 print('\\nNeighbour distances with multiple binary", "print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists", "4 print('\\nNeighbour distances with multiple binary hashes:') print(' -> Candidate", "{'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of permutations hash", "exact search) POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...')", "THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import", "matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f", "= engine_perm2.neighbours(query) dists = [x[2] for x in results] print(dists)", "Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index", "# Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First", "import time from nearpy import Engine from nearpy.distances import CosineDistance", "and/or sell # copies of the Software, and to permit", "permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) #", "(c) 2013 <NAME> # Permission is hereby granted, free of", "the rights # to use, copy, modify, merge, publish, distribute,", "engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0))", "= 20000 ########################################################## print('Performing indexing with HashPermutations...') t0 = time.time()", "as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine", "print(' -> Candidate count is %d' % engine_perm.candidate_count(query)) results =", "be included in # all copies or substantial portions of", "conditions: # The above copyright notice and this permission notice", "Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "multiple binary hashes:') print(' -> Candidate count is %d' %", "is hereby granted, free of charge, to any person obtaining", "HashPermutationMapper def example2(): # Dimension of feature space DIM =", "dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing", "engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for x in", "2013 <NAME> # Permission is hereby granted, free of charge,", "numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took", "numpy.random.randn(DIM) # Do random query on engine 3 print('\\nNeighbour distances", "count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists =", "dists = [x[2] for x in results] print(dists) # Real", "nearpy import Engine from nearpy.distances import CosineDistance from nearpy.hashes import", "Get random query vector query = numpy.random.randn(DIM) # Do random", "count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists =", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR", "= Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors", "Candidate count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists", "person obtaining a copy # of this software and associated", "without restriction, including without limitation the rights # to use,", "from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension", "= time.time() print('Indexing took %f seconds' % (t1-t0)) # Get", "engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some", "child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2", "so, subject to the following conditions: # The above copyright", "= numpy.random.randn(DIM) # Do random query on engine 3 print('\\nNeighbour", "k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create engine", "example2(): # Dimension of feature space DIM = 100 #", "= RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as", "engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some", "query vector query = numpy.random.randn(DIM) # Do random query on", "query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists =", "time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create", "count is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists =", "dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists)", "HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash permutations2 =", "# Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "binary hashes:') print(' -> Candidate count is %d' % engine_rbps.candidate_count(query))", "Candidate count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists", "neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query)", "permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash as", "took %f seconds' % (t1-t0)) # Get random query vector", "sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time()", "query on engine 3 print('\\nNeighbour distances with HashPermutations:') print(' ->", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists =", "= Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random vectors", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of feature", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "= CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ##########################################################", "because of exact search) POINTS = 20000 ########################################################## print('Performing indexing", "v = numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time()", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine", "engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some", "permutations2 = HashPermutationMapper('permut2') # Create binary hash as child hash", "# Permission is hereby granted, free of charge, to any", "of charge, to any person obtaining a copy # of", "= time.time() # Create permutations meta-hash permutations = HashPermutations('permut') #", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "merge, publish, distribute, sublicense, and/or sell # copies of the", "import numpy import scipy import unittest import time from nearpy", "engine_perm2.neighbours(query) dists = [x[2] for x in results] print(dists) #", "print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() # Create permutations", "NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT", "permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM,", "of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\",", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add", "or substantial portions of the Software. # THE SOFTWARE IS", "POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...') t0 =", "indexing with HashPermutations...') t0 = time.time() # Create permutations meta-hash", "# Dimension of feature space DIM = 100 # Number", "########################################################## print('\\nPerforming indexing with multiple binary hashes...') t0 = time.time()", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1 =", "engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count", "First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for i", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #", "vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v =", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "random query vector query = numpy.random.randn(DIM) # Do random query", "hashes = [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k,", "import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2():", "numpy import scipy import unittest import time from nearpy import", "hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add", "engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random", "feature space DIM = 100 # Number of data points", "lshashes=hashes, distance=CosineDistance()) # First index some random vectors matrix =", "FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE", "Add rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) #", "[] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) #", "14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash", "v engine_perm2.store_vector(v) t1 = time.time() print('Indexing took %f seconds' %", "substantial portions of the Software. # THE SOFTWARE IS PROVIDED", "on engine 3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate", "########################################################## print('Performing indexing with HashPermutations...') t0 = time.time() # Create", "the Software, and to permit persons to whom the Software", "lshashes=[permutations], distance=CosineDistance()) # First index some random vectors matrix =", "rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child hash", "random query on engine 3 print('\\nNeighbour distances with HashPermutations:') print('", "distances with HashPermutationMapper:') print(' -> Candidate count is %d' %", "% engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for x", "= engine_rbps.neighbours(query) dists = [x[2] for x in results] print(dists)", "in # all copies or substantial portions of the Software.", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "persons to whom the Software is # furnished to do", "query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming", "Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random vectors matrix", "print('\\nNeighbour distances with multiple binary hashes:') print(' -> Candidate count", "# Add rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2)", "permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds' % (t1-t0))", "following conditions: # The above copyright notice and this permission", "OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.", "associated documentation files (the \"Software\"), to deal # in the", "= {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of permutations", "query on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' ->", "with HashPermutations...') t0 = time.time() # Create permutations meta-hash permutations", "distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,))", "the following conditions: # The above copyright notice and this", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "DEALINGS IN # THE SOFTWARE. import numpy import scipy import", "to any person obtaining a copy # of this software", "with HashPermutationMapper:') print(' -> Candidate count is %d' % engine_perm2.candidate_count(query))", "Engine from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations,", "= 100 # Number of data points (dont do too", "RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child", "print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() #", "10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) #", "is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2]", "= v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds'", "of the Software, and to permit persons to whom the", "this software and associated documentation files (the \"Software\"), to deal", "binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f", "numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took", "Software is # furnished to do so, subject to the", "(dont do too much because of exact search) POINTS =", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) #", "# Number of data points (dont do too much because", "dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0", "to do so, subject to the following conditions: # The", "whom the Software is # furnished to do so, subject", "USE OR OTHER DEALINGS IN # THE SOFTWARE. import numpy", "sublicense, and/or sell # copies of the Software, and to", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "of feature space DIM = 100 # Number of data", "matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f", "# Get random query vector query = numpy.random.randn(DIM) # Do", "range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 =", "print('Performing indexing with HashPermutations...') t0 = time.time() # Create permutations", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "= sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 =", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "query = numpy.random.randn(DIM) # Do random query on engine 4", "in the Software without restriction, including without limitation the rights", "print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count is %d'", "binary hashes...') t0 = time.time() hashes = [] for k", "t0 = time.time() hashes = [] for k in range(20):", "# furnished to do so, subject to the following conditions:", "any person obtaining a copy # of this software and", "the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "ARISING FROM, # OUT OF OR IN CONNECTION WITH THE", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "shall be included in # all copies or substantial portions", "# -*- coding: utf-8 -*- # Copyright (c) 2013 <NAME>", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "restriction, including without limitation the rights # to use, copy,", "20000 ########################################################## print('Performing indexing with HashPermutations...') t0 = time.time() #", "<NAME> # Permission is hereby granted, free of charge, to", "SOFTWARE. import numpy import scipy import unittest import time from", "engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for x in", "import Engine from nearpy.distances import CosineDistance from nearpy.hashes import RandomBinaryProjections,", "including without limitation the rights # to use, copy, modify,", "copyright notice and this permission notice shall be included in", "engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1 = time.time()", "hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf =", "Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists =", "with multiple binary hashes:') print(' -> Candidate count is %d'", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "free of charge, to any person obtaining a copy #", "Create binary hash as child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14)", "files (the \"Software\"), to deal # in the Software without", "= Engine(DIM, lshashes=[permutations], distance=CosineDistance()) # First index some random vectors", "for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10)) # Create", "Create binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14)", "OTHER DEALINGS IN # THE SOFTWARE. import numpy import scipy", "query on engine 4 print('\\nNeighbour distances with multiple binary hashes:')", "query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists", "CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming", "t0 = time.time() # Create permutations meta-hash permutations2 = HashPermutationMapper('permut2')", "of data points (dont do too much because of exact", "on engine 4 print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate", "distances with HashPermutations:') print(' -> Candidate count is %d' %", "index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds' %", "numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] =", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for x in", "meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary hash as child", "do too much because of exact search) POINTS = 20000", "lshashes=[permutations2], distance=CosineDistance()) # First index some random vectors matrix =", "scipy import unittest import time from nearpy import Engine from", "is %d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2]", "= [] for k in range(20): hashes.append(RandomBinaryProjections('rbp_%d' % k, 10))", "meta-hash permutations = HashPermutations('permut') # Create binary hash as child", "rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp", "of this software and associated documentation files (the \"Software\"), to", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "utf-8 -*- # Copyright (c) 2013 <NAME> # Permission is", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "% (t1-t0)) # Get random query vector query = numpy.random.randn(DIM)", "HashPermutations('permut') # Create binary hash as child hash rbp_perm =", "engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index some random", "% k, 10)) # Create engine engine_rbps = Engine(DIM, lshashes=hashes,", "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS", "results = engine_perm.neighbours(query) dists = [x[2] for x in results]", "(the \"Software\"), to deal # in the Software without restriction,", "engine_rbps.store_vector(v) t1 = time.time() print('Indexing took %f seconds' % (t1-t0))", "hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations],", "hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm", "i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v)", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "i in range(POINTS): v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v)", "= numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM) matrix[i]", "charge, to any person obtaining a copy # of this", "permit persons to whom the Software is # furnished to", "to the following conditions: # The above copyright notice and", "% engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2] for x", "hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp as child", "%d' % engine_rbps.candidate_count(query)) results = engine_rbps.neighbours(query) dists = [x[2] for", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "import unittest import time from nearpy import Engine from nearpy.distances", "the Software is # furnished to do so, subject to", "do so, subject to the following conditions: # The above", "above copyright notice and this permission notice shall be included", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "limitation the rights # to use, copy, modify, merge, publish,", "this permission notice shall be included in # all copies", "########################################################## print('\\nPerforming indexing with HashPermutationMapper...') t0 = time.time() # Create", "Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random vectors matrix", "all copies or substantial portions of the Software. # THE", "= HashPermutationMapper('permut2') # Create binary hash as child hash rbp_perm2", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #", "-*- coding: utf-8 -*- # Copyright (c) 2013 <NAME> #", "time.time() # Create permutations meta-hash permutations = HashPermutations('permut') # Create", "without limitation the rights # to use, copy, modify, merge,", "portions of the Software. # THE SOFTWARE IS PROVIDED \"AS", "= numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update permuted", "permutations = HashPermutations('permut') # Create binary hash as child hash", "search) POINTS = 20000 ########################################################## print('Performing indexing with HashPermutations...') t0", "engine 3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count", "EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 = Engine(DIM,", "coding: utf-8 -*- # Copyright (c) 2013 <NAME> # Permission", "# in the Software without restriction, including without limitation the", "documentation files (the \"Software\"), to deal # in the Software", "matrix[i] = v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index()", "t1 = time.time() print('Indexing took %f seconds' % (t1-t0)) #", "# Create binary hash as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2',", "v = numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update", "= query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists = dists.reshape((-1,)) dists =", "neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix,query) dists =", "points (dont do too much because of exact search) POINTS", "= numpy.random.randn(DIM) matrix[i] = v engine_rbps.store_vector(v) t1 = time.time() print('Indexing", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT", "copies or substantial portions of the Software. # THE SOFTWARE", "sell # copies of the Software, and to permit persons", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance()) #", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #", "publish, distribute, sublicense, and/or sell # copies of the Software,", "CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ##########################################################", "= numpy.random.randn(DIM) matrix[i] = v engine_perm2.store_vector(v) t1 = time.time() print('Indexing", "rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} # Add rbp as child hash of", "rbp as child hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create", "indexing with HashPermutationMapper...') t0 = time.time() # Create permutations meta-hash", "def example2(): # Dimension of feature space DIM = 100", "engine 4 print('\\nNeighbour distances with multiple binary hashes:') print(' ->", "modify, merge, publish, distribute, sublicense, and/or sell # copies of", "as child hash rbp_perm2 = RandomBinaryProjections('rbp_perm2', 14) # Add rbp", "child hash rbp_perm = RandomBinaryProjections('rbp_perm', 14) rbp_conf = {'num_permutation':50,'beam_size':10,'num_neighbour':100} #", "OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION", "results = engine_rbps.neighbours(query) dists = [x[2] for x in results]", "x in results] print(dists) # Real neighbours print('\\nReal neighbour distances:')", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "-> Candidate count is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query)", "print(' -> Candidate count is %d' % engine_perm2.candidate_count(query)) results =", "= CosineDistance().distance(matrix, query) dists = dists.reshape((-1,)) dists = sorted(dists) print(dists[:10])", "Software, and to permit persons to whom the Software is", "nearpy.hashes import RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of", "# to use, copy, modify, merge, publish, distribute, sublicense, and/or", "query = numpy.random.randn(DIM) # Do random query on engine 3", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "hash of permutations hash permutations2.add_child_hash(rbp_perm2) # Create engine engine_perm2 =", "random vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v", "# Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM)) dists", "numpy.random.randn(DIM) # Do random query on engine 4 print('\\nNeighbour distances", "permutations.add_child_hash(rbp_perm, rbp_conf) # Create engine engine_perm = Engine(DIM, lshashes=[permutations], distance=CosineDistance())", "Create engine engine_perm2 = Engine(DIM, lshashes=[permutations2], distance=CosineDistance()) # First index", "\"Software\"), to deal # in the Software without restriction, including", "# THE SOFTWARE. import numpy import scipy import unittest import", "on engine 4 print('\\nNeighbour distances with multiple binary hashes:') print('", "permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing took %f seconds'", "print(dists) # Real neighbours print('\\nReal neighbour distances:') query = query.reshape((DIM))", "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "# Do random query on engine 4 print('\\nNeighbour distances with", "%d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query) dists = [x[2] for", "print('Indexing took %f seconds' % (t1-t0)) # Get random query", "# Copyright (c) 2013 <NAME> # Permission is hereby granted,", "RandomBinaryProjections, HashPermutations, HashPermutationMapper def example2(): # Dimension of feature space", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "too much because of exact search) POINTS = 20000 ##########################################################", "IN # THE SOFTWARE. import numpy import scipy import unittest", "distances with multiple binary hashes:') print(' -> Candidate count is", "# copies of the Software, and to permit persons to", "for x in results] print(dists) # Real neighbours print('\\nReal neighbour", "SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE", "= v engine_perm.store_vector(v) # Then update permuted index permutations.build_permuted_index() t1", "granted, free of charge, to any person obtaining a copy", "obtaining a copy # of this software and associated documentation", "Add rbp as child hash of permutations hash permutations.add_child_hash(rbp_perm, rbp_conf)", "TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN", "is # furnished to do so, subject to the following", "to whom the Software is # furnished to do so,", "matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS): v = numpy.random.randn(DIM)", "copy # of this software and associated documentation files (the", "THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "Permission is hereby granted, free of charge, to any person", "# First index some random vectors matrix = numpy.zeros((POINTS,DIM)) for", "some random vectors matrix = numpy.zeros((POINTS,DIM)) for i in range(POINTS):", "-*- # Copyright (c) 2013 <NAME> # Permission is hereby", "14) # Add rbp as child hash of permutations hash", "hashes:') print(' -> Candidate count is %d' % engine_rbps.candidate_count(query)) results", "is %d' % engine_perm.candidate_count(query)) results = engine_perm.neighbours(query) dists = [x[2]", "The above copyright notice and this permission notice shall be", "engine_rbps = Engine(DIM, lshashes=hashes, distance=CosineDistance()) # First index some random", "engine_rbps.neighbours(query) dists = [x[2] for x in results] print(dists) #", "dists.reshape((-1,)) dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with HashPermutationMapper...')", "dists = sorted(dists) print(dists[:10]) ########################################################## print('\\nPerforming indexing with multiple binary", "Do random query on engine 3 print('\\nNeighbour distances with HashPermutations:')", "HashPermutations...') t0 = time.time() # Create permutations meta-hash permutations =", "# Create permutations meta-hash permutations2 = HashPermutationMapper('permut2') # Create binary", "-> Candidate count is %d' % engine_perm2.candidate_count(query)) results = engine_perm2.neighbours(query)", "in results] print(dists) # Real neighbours print('\\nReal neighbour distances:') query", "query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists = dists.reshape((-1,))", "unittest import time from nearpy import Engine from nearpy.distances import", "neighbour distances:') query = query.reshape((DIM)) dists = CosineDistance().distance(matrix, query) dists", "subject to the following conditions: # The above copyright notice", "3 print('\\nNeighbour distances with HashPermutations:') print(' -> Candidate count is", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "print('\\nNeighbour distances with HashPermutationMapper:') print(' -> Candidate count is %d'", "Number of data points (dont do too much because of", "numpy.random.randn(DIM) matrix[i] = v engine_perm.store_vector(v) # Then update permuted index", "# Then update permuted index permutations.build_permuted_index() t1 = time.time() print('Indexing", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "to permit persons to whom the Software is # furnished", "# Create permutations meta-hash permutations = HashPermutations('permut') # Create binary", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING" ]
[ "discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect()", "q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\")", "= [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class", "#プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel'", "# Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os", "count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q)", "for q in smsd: q=str(q) if q==\"0\": count+=1 if count>0:", "# ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello", "await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i", "smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if q==\"0\": count+=1", "if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else:", "bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping bot.run(TOKEN) # Botのトークン", "in smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if", "try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self):", "in ky: i=str(i) if i == global_ch: count+=1 if count>0:", "INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。", "count=0 for q in smsd: q=str(q) if q==\"0\": count+=1 if", "クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): #", "else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class", "<コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot", "ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i) if i", "if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if", "'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self,", "count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd: q=str(q) if q==\"0\":", "Frameworkをインポート import traceback # エラー表示のためにインポート import os import discord import", "tasks # Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import", "else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def", "MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command)", "読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] #", "= \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help", "INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except", "conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i) if", "\"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return", "print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency *", "print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand):", "f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot =", "\"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\")", "i=str(i) if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0", "エラー表示のためにインポート import os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN']", "World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0", "\"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\"", "# エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception:", "'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def", "super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\"", "p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\")", "'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。", "ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World", "] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix,", "p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading", "== global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in", "print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading =", "print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\")", "ky: i=str(i) if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch)", "エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc()", "self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def", "# INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog)", "in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async", "os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [", "# スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in", "def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"]", "* 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky:", "Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID", "self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name)", "global_ch=\"gloch\" count=0 for i in ky: i=str(i) if i ==", "if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__()", "= \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self):", "import traceback # エラー表示のためにインポート import os import discord import r", "else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\"", "print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys()", "print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\")", "# エラー表示のためにインポート import os import discord import r TOKEN =", "= \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help", "__init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\" self.command_attrs[\"help\"] =", "スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS:", "import os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix", "{prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand())", "'__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping bot.run(TOKEN) #", "print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------')", "discord.ext import commands, tasks # Bot Commands Frameworkをインポート import traceback", "Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os import discord", "print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!')", "# discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms'))", "if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky)", "count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else:", "print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\"", "for cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() #", "return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__", "= os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS =", "prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval',", "traceback # エラー表示のためにインポート import os import discord import r TOKEN", "import commands, tasks # Bot Commands Frameworkをインポート import traceback #", "i in ky: i=str(i) if i == global_ch: count+=1 if", "smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True:", "1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in ky: i=str(i)", "# 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ]", "{prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__':", "commands, tasks # Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート", "p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True:", "i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q", "get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if", "(f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ ==", "command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for", "self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明:", "discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス", "'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): #", "<カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) #", "import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス #", "__name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping", "import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX']", "# MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) #", "== '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g. !ping bot.run(TOKEN)", "[ 'cogs.eval', 'cogs.glchat', 'cogs.gladd', 'cogs.gldel' ] # クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot):", "self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for i in", "class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。", "except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) #", "MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。", "= os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat',", "def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) #", "on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__) # discord.pyのバージョン", "JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category = \"その他\"", "if i == global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for", "traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id)", "for i in ky: i=str(i) if i == global_ch: count+=1", "if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。 e.g.", "q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\")", "r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。", "__init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。", "async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) # ボットのID print(discord.__version__)", "self.no_category = \"その他\" self.command_attrs[\"help\"] = \"コマンド一覧と簡単な説明を表示\" def get_ending_note(self): return (f\"各コマンドの説明:", "os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS = [ 'cogs.eval', 'cogs.glchat', 'cogs.gladd',", "help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog", "# Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前 print(self.user.id) #", "ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency", "!!') await self.change_presence(status=discord.Status.idle,activity=discord.Game(name=f'Ping:{self.ws.latency * 1000:.0f}ms')) conn=r.connect() ky=conn.keys() global_ch=\"gloch\" count=0 for", "count=0 for i in ky: i=str(i) if i == global_ch:", "cog in INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント", "else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else:", "INITIAL_EXTENSIONS: try: self.load_extension(cog) except Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def", "p=conn.sadd(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self):", "#MyBotのインスタンス化及び起動処理。 if __name__ == '__main__': bot = MyBot(command_prefix=prefix,help_command=JapaneseHelpCommand()) # command_prefixはコマンドの最初の文字として使うもの。", "print(\"異常発生\") class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category", "Exception: traceback.print_exc() # Botの準備完了時に呼び出されるイベント async def on_ready(self): print(self.user.name) # ボットの名前", "TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix = os.environ['DISCORD_BOT_PREFIX'] #プレフィックス # 読み込むコグの名前を格納しておく。 INITIAL_EXTENSIONS", "super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 # エラーが発生した場合は、エラー内容を表示。 for cog in INITIAL_EXTENSIONS: try:", "os import discord import r TOKEN = os.environ['DISCORD_BOT_TOKEN'] prefix =", "if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else: p=conn.sadd(global_ch,\"0\") if", "# ボットのID print(discord.__version__) # discord.pyのバージョン print('----------------') print('Hello World !!') await", "# クラスの定義。ClientのサブクラスであるBotクラスを継承。 class MyBot(commands.Bot): # MyBotのコンストラクタ。 def __init__(self, command_prefix, help_command):", "global_ch: count+=1 if count>0: smsd=conn.smembers(global_ch) count=0 for q in smsd:", "count>0: p=conn.srem(global_ch,\"0\") if p==True: print(\"正常起動\") else: print(\"異常発生\") else: print(ky) else:", "def get_ending_note(self): return (f\"各コマンドの説明: {prefix}help <コマンド名>\\n\" f\"各カテゴリの説明: {prefix}help <カテゴリ名>\\n\") #MyBotのインスタンス化及び起動処理。", "def __init__(self, command_prefix, help_command): # スーパークラスのコンストラクタに値を渡して実行。 super().__init__(command_prefix,help_command) # INITIAL_COGSに格納されている名前から、コグを読み込む。 #", "class JapaneseHelpCommand(commands.DefaultHelpCommand): def __init__(self): super().__init__() self.commands_heading = \"コマンド:\" self.no_category =", "Bot Commands Frameworkをインポート import traceback # エラー表示のためにインポート import os import", "from discord.ext import commands, tasks # Bot Commands Frameworkをインポート import", "q in smsd: q=str(q) if q==\"0\": count+=1 if count>0: p=conn.srem(global_ch,\"0\")" ]
[ "= px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main", "cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # ===========================================", "code works on both python 2 and python 3 from", "to download this document as a Jupyter Notebook (button at", "importance. Furthermore, SVD is also very well suited for data", "title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the", "to get back the complex valued eigenvectors. # # **Pycroscopy", "url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file =", "all relevant links to the source dataset and other ancillary", "Functional Imaging of Materials * Center for Nanophase Materials Sciences", "the two spatial dimensions (x, y) have been collapsed to", "your own data, you can skip this cell and provide", "the types of spectral responses present in the # data.", "it is a good method for quickly # visualizing the", "as abundance maps. Complex valued abundance maps are not physical.", "fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close", "own data instead. # When using your own data, you", "======================= * Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib", "the optimal labeling # (ie., assignment of each spectra as", "# Import packages # Ensure that this code works on", "= px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp", "positive real values. It operates by approximate determination of #", "two # dimensional grid of spatial locations. Thus, this is", "with pip.') import pip install('pycroscopy') import pycroscopy as px from", "as plt # for downloading files: import wget import os", "# dimensional grid of spatial locations. Thus, this is a", "Clustering # ==================== # # KMeans clustering is a quick", "that this code works on both python 2 and python", "are realized through the ability to seamlessly perform these analyses", "the variable - data_file_path data_file_path = 'temp_um.h5' # download the", "such that the within-cluster # sum of squares is minimized.", "that can be applied to complex-valued datasets, NMF only works", "on data with positive real values. It operates by approximate", "of spatial locations. Thus, this is a three dimensional dataset", "each of these components # # Advantage of pycroscopy: #", "interpretation. Nonetheless, it is a good method for quickly #", "we need to reshape the abundance maps: abun_maps = np.reshape(h5_u[:,", "(regardless of origin, size, complexity) and storing the results back", "data such that it is real-valued only. # # One", "each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with", "data transformations (both for the source dataset and the eigenvectors)", "of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn) *", "S - Variance or importance of each of these components", "Advantage of pycroscopy: # ------------------------ # Notice that we are", "num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize", "KMeans clustering is a quick and easy method to determine", "======== # # In this example, we will work on", "perform basic data analysis, including: ======================================================================================== * KMeans Clustering *", "px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) #", "# # SVD is an eigenvector decomposition that is defined", "back the complex valued eigenvectors. # # **Pycroscopy handles all", "significant) components. # # SVD results in three matrices: #", "and provide the path to your data using the variable", "= h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF)", "to be treated as the concatenation of the real and", "3. Non-negative Matrix Factorization (NMF) # =========================================== # # NMF,", "this notebook we load some spectral data, and perform basic", "use your own data instead. # When using your own", "Component Analysis Software Prerequisites: ======================= * Standard distribution of **Anaconda**", "numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy** : Though", "three dimensional dataset that has been flattened to a two", "**Pycroscopy handles all these data transformations (both for the source", "np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps',", "# .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means", "Complex valued abundance maps are not physical. # Thus, one", "clustering is a quick and easy method to determine the", "take the amplitude component of the spectral data num_comps =", "# # **Pycroscopy handles all these data transformations (both for", "Prerequisites: ======================= * Standard distribution of **Anaconda** (includes numpy, scipy,", "variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the", "decomposition method, but a basic clustering method. The user inputs", "as belonging to the k<sup>th</sup> set) such that the within-cluster", "real-valued eigenvectors would need to be treated as the concatenation", "px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the X", "KMeans from sklearn.decomposition import NMF import subprocess import sys def", "print('Data currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label", "# In this example, we will work on a **Band", "machine learning, spectral unmixing algorithms, etc. only accept data that", "axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #')", "first N (most significant) components. # # SVD results in", "Sciences Oak Ridge National Laboratory, Oak Ridge TN 37831, USA", "of the imaginary component before passing to SVD. # After", "print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000']", "basic data analysis, including: ======================================================================================== * KMeans Clustering * Non-negative", "this is a three dimensional dataset that has been flattened", "install('pycroscopy') import pycroscopy as px from pycroscopy.viz import cluster_utils #####################################################################################", "the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path =", "real-valued only. # # One solution is to stack the", "be restructured to get back the complex valued eigenvectors. #", "true capabilities are realized through the ability to seamlessly perform", "sorted in descending # order of variance or importance. Furthermore,", "in descending order # * U - corresponding abundance maps", "the path to your data using the variable - data_file_path", "h5 file including all relevant links to the source dataset", "basic clustering method. The user inputs the number of #", "or non-negative matrix factorization, is a method that is useful", "determination of # factors (matrices) W and H, given a", "freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF", "using the variable - data_file_path data_file_path = 'temp_um.h5' # download", "# order of variance or importance. Furthermore, SVD is also", "files: import h5py # Plotting and visualization: import matplotlib.pyplot as", "values as is to SVD would result in # complex", "KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response']", "reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity':", "factors (matrices) W and H, given a matrix V, as", "= 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD)", "National Laboratory, Oak Ridge TN 37831, USA In this notebook", "complexity) and storing the results back into the same dataset", "the magnitude of the imaginary component before passing to SVD.", "importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of", "the variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note", "such that it is real-valued only. # # One solution", "# The package used for creating and manipulating HDF5 files:", "import wget import os # multivariate analysis: from sklearn.cluster import", "portion of the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps,", "px from pycroscopy.viz import cluster_utils ##################################################################################### # The Data #", "* Principal Component Analysis Software Prerequisites: ======================= * Standard distribution", "Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit", "data analysis, including: ======================================================================================== * KMeans Clustering * Non-negative Matrix", "# Ensure that this code works on both python 2", "init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec,", "model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components',", "h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting", "interpretation of eigenvectors and abundance maps from # SVD requires", "optimal labeling # (ie., assignment of each spectra as belonging", "file available on our GitHub project page by default. You", "axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete the h5_file", "etc. only accept data that is # formatted in the", "pycroscopy handles compound / complex valued datasets everywhere possible #", "in interpretation. Nonetheless, it is a good method for quickly", "at the bottom of the page) and use your own", "_ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) #####################################################################################", "quickly # visualizing the major trends in the dataset since", "that the within-cluster # sum of squares is minimized. #", "both python 2 and python 3 from __future__ import division,", "* Center for Nanophase Materials Sciences Oak Ridge National Laboratory,", "is a good method for quickly # visualizing the major", "Clustering * Non-negative Matrix Factorization * Principal Component Analysis Software", "from SVD back to # the same source h5 file", "import pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz import", "# The Data # ======== # # In this example,", "spectral data, and perform basic data analysis, including: ======================================================================================== *", "complex valued datasets everywhere possible # # Furthermore, while it", "U - corresponding abundance maps # * S - Variance", "the real and imaginary # components. So, the eigenvectors would", "complex values as is to SVD would result in #", "will be using an data file available on our GitHub", "through the ability to seamlessly perform these analyses on any", "are working with a complex valued dataset. Passing the complex", "##################################################################################### # 1. Singular Value Decomposition (SVD) # ===================================== #", "relevant links to the source dataset and other ancillary datasets", "= plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label,", "basic numeric computation: import numpy as np # The package", "dimensional grid of spatial locations. Thus, this is a three", "same source h5 file including all relevant links to the", "# factors (matrices) W and H, given a matrix V,", "online files: # finally import pycroscopy: try: import pycroscopy as", "Software Prerequisites: ======================= * Standard distribution of **Anaconda** (includes numpy,", "reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols,", "data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:')", "Thus, one would need to restructure the data such that", "/ complex valued datasets everywhere possible # # Furthermore, while", "* KMeans Clustering * Non-negative Matrix Factorization * Principal Component", "creating and manipulating HDF5 files: import h5py # Plotting and", "# # Set the number of clusters below num_clusters =", "this code works on both python 2 and python 3", "we load some spectral data, and perform basic data analysis,", "install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for downloading", "= 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path,", "V, as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png #", "since the resultant eigenvectors are sorted in descending # order", "for the source dataset and the eigenvectors) # automatically.** In", "real and imaginary # components. So, the eigenvectors would need", "as well as abundance maps. Complex valued abundance maps are", "assignment of each spectra as belonging to the k<sup>th</sup> set)", "by approximate determination of # factors (matrices) W and H,", "works on data with positive real values. It operates by", "as px from pycroscopy.viz import cluster_utils ##################################################################################### # The Data", "this document as a Jupyter Notebook (button at the bottom", "Nonetheless, it is a good method for quickly # visualizing", "method for quickly # visualizing the major trends in the", "trends in the dataset since the resultant eigenvectors are sorted", "dimensional matrix in accordance with the pycroscopy data format. #", "np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape) x_label =", "for data cleaning through # the reconstruction of the dataset", "variable - data_file_path data_file_path = 'temp_um.h5' # download the data", "# Fortunately, all statistical analysis, machine learning, spectral unmixing algorithms,", "handles all these data transformations (both for the source dataset", "source dataset and the eigenvectors) # automatically.** In general, pycroscopy", "and easy method to determine the types of spectral responses", "# SVD requires care and caution in interpretation. Nonetheless, it", "the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0)", "while it is not discussed in this example, pycroscopy also", ".. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that", "NMF import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\",", "dataset and the eigenvectors) # automatically.** In general, pycroscopy handles", "The algorithm proceeds to find the optimal labeling # (ie.,", "# # Fortunately, all statistical analysis, machine learning, spectral unmixing", "title_yoffset=0.95) # Visualize the variance / statistical importance of each", "as a Jupyter Notebook (button at the bottom of the", "given a matrix V, as shown below # # ..", "Decomposition (SVD) # ===================================== # # SVD is an eigenvector", "data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig,", "non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps", "N (most significant) components. # # SVD results in three", "each spectra as belonging to the k<sup>th</sup> set) such that", "the ability to seamlessly perform these analyses on any imaging", "Data # ======== # # In this example, we will", "care and caution in interpretation. Nonetheless, it is a good", "real values. It operates by approximate determination of # factors", "the results back into the same dataset among other things", "matrix. # # We will be using an data file", "sorted by variance in descending order # * U -", "be applied to complex-valued datasets, NMF only works on non-negative", "the same manner of [position x spectra] in a two", "decomposition that is defined statistically, and therefore typically produces #", "# # In this example, we will work on a", "dimensional matrix. # # We will be using an data", "abundance maps. Complex valued abundance maps are not physical. #", "all statistical analysis, machine learning, spectral unmixing algorithms, etc. only", "importance of each of these components # # Advantage of", "**pycroscopy** : Though pycroscopy is mainly used here for plotting", "h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file)", "abundance maps # * S - Variance or importance of", "components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label,", "results from SVD back to # the same source h5", "not a decomposition method, but a basic clustering method. The", "from advanced atomic force microscopes. In this dataset, a spectra", "spectra as belonging to the k<sup>th</sup> set) such that the", "eigenvectors) # automatically.** In general, pycroscopy handles compound / complex", "operates by approximate determination of # factors (matrices) W and", "import KMeans from sklearn.decomposition import NMF import subprocess import sys", "cluster_utils ##################################################################################### # The Data # ======== # # In", "Set the number of clusters below num_clusters = 4 estimator", "# Advantage of pycroscopy: # ------------------------ # Notice that we", "main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'})", "the first N (most significant) components. # # SVD results", "on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset", "your own data instead. # When using your own data,", "results in three matrices: # # * V - Eigenvectors", "in the # data. It is not a decomposition method,", "with a complex valued dataset. Passing the complex values as", "purposes only, it's true capabilities are realized through the ability", "valued abundance maps are not physical. # Thus, one would", "analysis, including: ======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization", "algorithm proceeds to find the optimal labeling # (ie., assignment", "# We will be using an data file available on", "h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3.", "model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF", "px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12)", "print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic", "that we are working with a complex valued dataset. Passing", "towards unmixing of spectral # data. It only works on", "descending # order of variance or importance. Furthermore, SVD is", "Laboratory, Oak Ridge TN 37831, USA In this notebook we", "of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] #", "h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization (NMF) #", "# Furthermore, while it is not discussed in this example,", "Extracting the X axis - vector of frequencies h5_spec_vals =", "matrix V, as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png", "= 4 # get the non-negative portion of the dataset", "file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path,", "'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+')", "a good method for quickly # visualizing the major trends", "number of clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main,", "sci-kit learn) * **pycroscopy** : Though pycroscopy is mainly used", "It only works on data with positive real values. It", "for downloading files: import wget import os # multivariate analysis:", "sklearn.cluster import KMeans from sklearn.decomposition import NMF import subprocess import", "SVD, the real-valued eigenvectors would need to be treated as", "is also very well suited for data cleaning through #", "# Unlike SVD and k-Means that can be applied to", "the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1))", "download the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path", "the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors',", "eigenvectors are sorted in descending # order of variance or", "is minimized. # # Set the number of clusters below", "of squares is minimized. # # Set the number of", "================================================================= Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for", "The package used for creating and manipulating HDF5 files: import", "= px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v", "title='Note the exponential drop of variance with number of components')", "to the source dataset and other ancillary datasets decomposer =", "for each position in a two # dimensional grid of", "project page by default. You are encouraged # to download", "y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition", "in a two dimensional matrix. # # We will be", "on any imaging dataset (regardless of origin, size, complexity) and", "determine the types of spectral responses present in the #", "num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main)", "num_comps = 4 # get the non-negative portion of the", "'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:',", "among other things \"\"\" # Import packages # Ensure that", "- vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec =", "endmembers as well as abundance maps. Complex valued abundance maps", "matrices: # # * V - Eigenvectors sorted by variance", "(matrices) W and H, given a matrix V, as shown", "the dataset since the resultant eigenvectors are sorted in descending", "We will be using an data file available on our", "complex valued eigenvectors / endmembers as well as abundance maps.", "= h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two spatial", "visualization: import matplotlib.pyplot as plt # for downloading files: import", "(a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD) # =====================================", "Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance", "complex-valued datasets, NMF only works on non-negative datasets. # For", "packages # Ensure that this code works on both python", "pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz import cluster_utils", "(sets) to partition the data into. The algorithm proceeds to", "a complex valued dataset. Passing the complex values as is", "# Set the number of clusters below num_clusters = 4", "page by default. You are encouraged # to download this", "HDF5 files: import h5py # Plotting and visualization: import matplotlib.pyplot", "h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp", "(ie., assignment of each spectra as belonging to the k<sup>th</sup>", "plt # for downloading files: import wget import os #", "# # One solution is to stack the real value", "\"install\", package]) # Package for downloading online files: # finally", "from # SVD requires care and caution in interpretation. Nonetheless,", "valued dataset. Passing the complex values as is to SVD", "number of components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9,", "as px except ImportError: print('pycroscopy not found. Will install with", "to be restructured to get back the complex valued eigenvectors.", "realized through the ability to seamlessly perform these analyses on", "and k-Means that can be applied to complex-valued datasets, NMF", "matplotlib and sci-kit learn) * **pycroscopy** : Though pycroscopy is", "dataset since the resultant eigenvectors are sorted in descending #", "(num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single',", "microscopes. In this dataset, a spectra was collected for each", "each position in a two # dimensional grid of spatial", "num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the", "and H, given a matrix V, as shown below #", "Jupyter Notebook (button at the bottom of the page) and", "USA In this notebook we load some spectral data, and", "is a method that is useful towards unmixing of spectral", "to the k<sup>th</sup> set) such that the within-cluster # sum", "eigenvectors. # # **Pycroscopy handles all these data transformations (both", "maps are not physical. # Thus, one would need to", "variance or importance. Furthermore, SVD is also very well suited", "not physical. # Thus, one would need to restructure the", "Passing the complex values as is to SVD would result", "axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### #", "# * S - Variance or importance of each of", "# # Furthermore, while it is not discussed in this", "and visualization: import matplotlib.pyplot as plt # for downloading files:", "# Package for downloading online files: # finally import pycroscopy:", "x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering", "# =========================================== # # NMF, or non-negative matrix factorization, is", "So, the eigenvectors would need to be restructured to get", "'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular", "by variance in descending order # * U - corresponding", "decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U']", "color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical importance", "h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the", "set) such that the within-cluster # sum of squares is", "= np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance", "responses present in the # data. It is not a", "in three matrices: # # * V - Eigenvectors sorted", "unicode_literals # basic numeric computation: import numpy as np #", "# clusters (sets) to partition the data into. The algorithm", "# One solution is to stack the real value followed", "result in # complex valued eigenvectors / endmembers as well", "# the reconstruction of the dataset using only the first", "NMF only works on non-negative datasets. # For illustrative purposes,", "requires care and caution in interpretation. Nonetheless, it is a", "px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference", "method to determine the types of spectral responses present in", "that is useful towards unmixing of spectral # data. It", "grid of spatial locations. Thus, this is a three dimensional", "default. You are encouraged # to download this document as", "= px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### #", "non-negative matrix factorization, is a method that is useful towards", "import numpy as np # The package used for creating", "these data transformations (both for the source dataset and the", "statistical analysis, machine learning, spectral unmixing algorithms, etc. only accept", "axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12)", "When using your own data, you can skip this cell", "are encouraged # to download this document as a Jupyter", "{'quantity': 'Deflection', 'units': 'V'}) # Extracting the X axis -", "not found. Will install with pip.') import pip install('pycroscopy') import", "collapsed to one, we need to reshape the abundance maps:", "data instead. # When using your own data, you can", "abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps,", "k<sup>th</sup> set) such that the within-cluster # sum of squares", "force microscopes. In this dataset, a spectra was collected for", "Imaging of Materials * Center for Nanophase Materials Sciences Oak", "source h5 file including all relevant links to the source", "* **pycroscopy** : Though pycroscopy is mainly used here for", "of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance", "estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels']", "dimensional dataset that has been flattened to a two #", "would need to be restructured to get back the complex", "on non-negative datasets. # For illustrative purposes, we will only", "import cluster_utils ##################################################################################### # The Data # ======== # #", "found. Will install with pip.') import pip install('pycroscopy') import pycroscopy", "for quickly # visualizing the major trends in the dataset", "will only take the amplitude component of the spectral data", "the dataset using only the first N (most significant) components.", "used here for plotting purposes only, it's true capabilities are", "the same dataset among other things \"\"\" # Import packages", "the non-negative portion of the dataset data_mat = np.abs(h5_main) model", "values. It operates by approximate determination of # factors (matrices)", "# For illustrative purposes, we will only take the amplitude", "Non-negative Matrix Factorization * Principal Component Analysis Software Prerequisites: =======================", "imaginary component before passing to SVD. # After SVD, the", "data num_comps = 4 # get the non-negative portion of", "you can skip this cell and provide the path to", "partition the data into. The algorithm proceeds to find the", "analysis, machine learning, spectral unmixing algorithms, etc. only accept data", "# multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition import", "a two # dimensional grid of spatial locations. Thus, this", "own data, you can skip this cell and provide the", "data_file_path = 'temp_um.h5' # download the data file from Github:", "and caution in interpretation. Nonetheless, it is a good method", "before passing to SVD. # After SVD, the real-valued eigenvectors", "reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical", "currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label =", "the within-cluster # sum of squares is minimized. # #", "links to the source dataset and other ancillary datasets decomposer", "V - Eigenvectors sorted by variance in descending order #", "page) and use your own data instead. # When using", "* S - Variance or importance of each of these", "of shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude", "with number of components') # Visualize the eigenvectors: _ =", "- data_file_path data_file_path = 'temp_um.h5' # download the data file", "After SVD, the real-valued eigenvectors would need to be treated", "# # NMF, or non-negative matrix factorization, is a method", "back into the same dataset among other things \"\"\" #", "was collected for each position in a two # dimensional", "sum of squares is minimized. # # Set the number", "factorization, is a method that is useful towards unmixing of", "major trends in the dataset since the resultant eigenvectors are", "4 # get the non-negative portion of the dataset data_mat", "advanced atomic force microscopes. In this dataset, a spectra was", "mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp =", "complex valued eigenvectors. # # **Pycroscopy handles all these data", "W and H, given a matrix V, as shown below", "formatted in the same manner of [position x spectra] in", "defined statistically, and therefore typically produces # non-physical eigenvectors. Consequently,", "Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional Imaging", "data_file_path data_file_path = 'temp_um.h5' # download the data file from", "to restructure the data such that it is real-valued only.", "of components') # Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :],", "writes back the results from SVD back to # the", "method that is useful towards unmixing of spectral # data.", "of variance or importance. Furthermore, SVD is also very well", "to your data using the variable - data_file_path data_file_path =", "algorithms, etc. only accept data that is # formatted in", "\"-m\", \"pip\", \"install\", package]) # Package for downloading online files:", "import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\",", "= 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1.", "eigenvector decomposition that is defined statistically, and therefore typically produces", "we are working with a complex valued dataset. Passing the", "to SVD would result in # complex valued eigenvectors /", "= px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the", "is to stack the real value followed by the magnitude", "eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False)", "data into. The algorithm proceeds to find the optimal labeling", "within-cluster # sum of squares is minimized. # # Set", "example, pycroscopy also writes back the results from SVD back", "accept data that is # formatted in the same manner", "np # The package used for creating and manipulating HDF5", "downloading online files: # finally import pycroscopy: try: import pycroscopy", "shape:', h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)'", "the data into. The algorithm proceeds to find the optimal", "eigenvectors and abundance maps from # SVD requires care and", "on our GitHub project page by default. You are encouraged", "perform these analyses on any imaging dataset (regardless of origin,", "Ridge TN 37831, USA In this notebook we load some", "package used for creating and manipulating HDF5 files: import h5py", "with the pycroscopy data format. # # Fortunately, all statistical", "# formatted in the same manner of [position x spectra]", "typically produces # non-physical eigenvectors. Consequently, the interpretation of eigenvectors", "magnitude of the imaginary component before passing to SVD. #", ":], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans", "is to SVD would result in # complex valued eigenvectors", "maps. Complex valued abundance maps are not physical. # Thus,", "to determine the types of spectral responses present in the", "of spectral # data. It only works on data with", "only. # # One solution is to stack the real", "model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5,", "physical. # Thus, one would need to restructure the data", "install with pip.') import pip install('pycroscopy') import pycroscopy as px", "to SVD. # After SVD, the real-valued eigenvectors would need", "the major trends in the dataset since the resultant eigenvectors", "**Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired", "matplotlib.pyplot as plt # for downloading files: import wget import", "\"\"\" ================================================================= Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute", "two # dimensional matrix in accordance with the pycroscopy data", "path to your data using the variable - data_file_path data_file_path", "are sorted in descending # order of variance or importance.", "the real-valued eigenvectors would need to be treated as the", "example, we will work on a **Band Excitation Piezoresponse Force", "Import packages # Ensure that this code works on both", "In this dataset, a spectra was collected for each position", "# # KMeans clustering is a quick and easy method", "an eigenvector decomposition that is defined statistically, and therefore typically", "variance with number of components') # Visualize the eigenvectors: _", "<NAME>, <NAME> * Institute for Functional Imaging of Materials *", "Eigenvectors sorted by variance in descending order # * U", "have been collapsed to one, we need to reshape the", "You are encouraged # to download this document as a", "approximate determination of # factors (matrices) W and H, given", "only take the amplitude component of the spectral data num_comps", "for creating and manipulating HDF5 files: import h5py # Plotting", "estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### #", "all these data transformations (both for the source dataset and", "find the optimal labeling # (ie., assignment of each spectra", "KMeans Clustering * Non-negative Matrix Factorization * Principal Component Analysis", "# SVD is an eigenvector decomposition that is defined statistically,", "skip this cell and provide the path to your data", "collected for each position in a two # dimensional grid", "non-negative datasets. # For illustrative purposes, we will only take", "as the concatenation of the real and imaginary # components.", "spectra] in a two dimensional matrix. # # We will", "from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None)", "/ statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential", "# basic numeric computation: import numpy as np # The", "spectral # data. It only works on data with positive", "ImportError: print('pycroscopy not found. Will install with pip.') import pip", "files: import wget import os # multivariate analysis: from sklearn.cluster", "# 1. Singular Value Decomposition (SVD) # ===================================== # #", "only the first N (most significant) components. # # SVD", "# * U - corresponding abundance maps # * S", "the source dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main,", "bottom of the page) and use your own data instead.", "compound / complex valued datasets everywhere possible # # Furthermore,", "# KMeans clustering is a quick and easy method to", "valued datasets everywhere possible # # Furthermore, while it is", "print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters: num_rows", "4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels =", "Plotting and visualization: import matplotlib.pyplot as plt # for downloading", "px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp =", "SVD back to # the same source h5 file including", "sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package", "need to restructure the data such that it is real-valued", "# ------------------------ # Notice that we are working with a", "works on non-negative datasets. # For illustrative purposes, we will", "(button at the bottom of the page) and use your", "we will work on a **Band Excitation Piezoresponse Force Microscopy", "* Non-negative Matrix Factorization * Principal Component Analysis Software Prerequisites:", "to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection',", "to stack the real value followed by the magnitude of", "<NAME>, <NAME>, <NAME> * Institute for Functional Imaging of Materials", "clusters (sets) to partition the data into. The algorithm proceeds", "is not discussed in this example, pycroscopy also writes back", "Furthermore, SVD is also very well suited for data cleaning", "the complex values as is to SVD would result in", "spatial dimensions (x, y) have been collapsed to one, we", "and therefore typically produces # non-physical eigenvectors. Consequently, the interpretation", "= 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels", "is not a decomposition method, but a basic clustering method.", "unmixing algorithms, etc. only accept data that is # formatted", "concatenation of the real and imaginary # components. So, the", "of the page) and use your own data instead. #", "user inputs the number of # clusters (sets) to partition", "a method that is useful towards unmixing of spectral #", "of each of these components # # Advantage of pycroscopy:", "works on both python 2 and python 3 from __future__", "k-Means that can be applied to complex-valued datasets, NMF only", "component of the spectral data num_comps = 4 # get", "using your own data, you can skip this cell and", "**Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy**", "axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec", "37831, USA In this notebook we load some spectral data,", "here for plotting purposes only, it's true capabilities are realized", "dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group", "(x, y) have been collapsed to one, we need to", "y) have been collapsed to one, we need to reshape", "a matrix V, as shown below # # .. image::", "to complex-valued datasets, NMF only works on non-negative datasets. #", "pycroscopy as px from pycroscopy.viz import cluster_utils ##################################################################################### # The", "would need to be treated as the concatenation of the", "be using an data file available on our GitHub project", "dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) #", "need to be restructured to get back the complex valued", "manipulating HDF5 files: import h5py # Plotting and visualization: import", "the number of # clusters (sets) to partition the data", "print('pycroscopy not found. Will install with pip.') import pip install('pycroscopy')", "Value Decomposition (SVD) # ===================================== # # SVD is an", "passing to SVD. # After SVD, the real-valued eigenvectors would", "everywhere possible # # Furthermore, while it is not discussed", "h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data", "python 3 from __future__ import division, print_function, absolute_import, unicode_literals #", "absolute_import, unicode_literals # basic numeric computation: import numpy as np", "Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols =", "# Getting a reference to the main dataset: h5_main =", "\"pip\", \"install\", package]) # Package for downloading online files: #", "random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_,", "eigenvectors would need to be treated as the concatenation of", "(SVD) # ===================================== # # SVD is an eigenvector decomposition", "has been flattened to a two # dimensional matrix in", "division, print_function, absolute_import, unicode_literals # basic numeric computation: import numpy", "'units': 'V'}) # Extracting the X axis - vector of", "distribution of **Anaconda** (includes numpy, scipy, matplotlib and sci-kit learn)", "= h5_svd_group['S'] # Since the two spatial dimensions (x, y)", "import pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy", "format. # # Fortunately, all statistical analysis, machine learning, spectral", "sklearn.decomposition import NMF import subprocess import sys def install(package): subprocess.call([sys.executable,", "value followed by the magnitude of the imaginary component before", "imaginary # components. So, the eigenvectors would need to be", "method. The user inputs the number of # clusters (sets)", "Principal Component Analysis Software Prerequisites: ======================= * Standard distribution of", "data using the variable - data_file_path data_file_path = 'temp_um.h5' #", "with positive real values. It operates by approximate determination of", "Furthermore, while it is not discussed in this example, pycroscopy", "need to be treated as the concatenation of the real", "px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters:", "In general, pycroscopy handles compound / complex valued datasets everywhere", "numeric computation: import numpy as np # The package used", "X axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1]", "learning, spectral unmixing algorithms, etc. only accept data that is", "used for creating and manipulating HDF5 files: import h5py #", "spectral unmixing algorithms, etc. only accept data that is #", "* U - corresponding abundance maps # * S -", "order # * U - corresponding abundance maps # *", "# complex valued eigenvectors / endmembers as well as abundance", "spatial locations. Thus, this is a three dimensional dataset that", "and imaginary # components. So, the eigenvectors would need to", "# non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance", "using an data file available on our GitHub project page", "(most significant) components. # # SVD results in three matrices:", "only, it's true capabilities are realized through the ability to", "'grid_num_cols') # Getting a reference to the main dataset: h5_main", "= px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently", "components. So, the eigenvectors would need to be restructured to", "(BE-PFM)** imaging dataset # acquired from advanced atomic force microscopes.", "[position x spectra] in a two dimensional matrix. # #", "the spectral data num_comps = 4 # get the non-negative", "components. # # SVD results in three matrices: # #", "available on our GitHub project page by default. You are", "px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with number of", "h5_file['Measurement_000'] # Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows')", "Materials * Center for Nanophase Materials Sciences Oak Ridge National", "data cleaning through # the reconstruction of the dataset using", "Nanophase Materials Sciences Oak Ridge National Laboratory, Oak Ridge TN", "= estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) #####################################################################################", "NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis,", "# # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and", "Materials Sciences Oak Ridge National Laboratory, Oak Ridge TN 37831,", "locations. Thus, this is a three dimensional dataset that has", "restructured to get back the complex valued eigenvectors. # #", "datasets, NMF only works on non-negative datasets. # For illustrative", "analyses on any imaging dataset (regardless of origin, size, complexity)", "title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ====================", "mainly used here for plotting purposes only, it's true capabilities", "into the same dataset among other things \"\"\" # Import", "3 from __future__ import division, print_function, absolute_import, unicode_literals # basic", "two dimensional matrix. # # We will be using an", "the page) and use your own data instead. # When", "data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting", "been collapsed to one, we need to reshape the abundance", "types of spectral responses present in the # data. It", "back to # the same source h5 file including all", "to find the optimal labeling # (ie., assignment of each", "# ==================== # # KMeans clustering is a quick and", "unmixing of spectral # data. It only works on data", "quick and easy method to determine the types of spectral", "fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete the", "# NMF, or non-negative matrix factorization, is a method that", "px except ImportError: print('pycroscopy not found. Will install with pip.')", "therefore typically produces # non-physical eigenvectors. Consequently, the interpretation of", "of these components # # Advantage of pycroscopy: # ------------------------", "dataset. Passing the complex values as is to SVD would", "h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix Factorization", "os # multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition", "multivariate analysis: from sklearn.cluster import KMeans from sklearn.decomposition import NMF", "also very well suited for data cleaning through # the", "Institute for Functional Imaging of Materials * Center for Nanophase", "===================================== # # SVD is an eigenvector decomposition that is", "but a basic clustering method. The user inputs the number", "caution in interpretation. Nonetheless, it is a good method for", "things \"\"\" # Import packages # Ensure that this code", "2 and python 3 from __future__ import division, print_function, absolute_import,", "to # the same source h5 file including all relevant", "storing the results back into the same dataset among other", "h5_svd_group['S'] # Since the two spatial dimensions (x, y) have", "these components # # Advantage of pycroscopy: # ------------------------ #", "the real value followed by the magnitude of the imaginary", "one, we need to reshape the abundance maps: abun_maps =", "minimized. # # Set the number of clusters below num_clusters", "analysis: from sklearn.cluster import KMeans from sklearn.decomposition import NMF import", "# * V - Eigenvectors sorted by variance in descending", "It operates by approximate determination of # factors (matrices) W", "visualizing the major trends in the dataset since the resultant", "axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and", "as shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # #", "Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired from", "for downloading online files: # finally import pycroscopy: try: import", "reconstruction of the dataset using only the first N (most", "is defined statistically, and therefore typically produces # non-physical eigenvectors.", "of Materials * Center for Nanophase Materials Sciences Oak Ridge", "non-negative portion of the dataset data_mat = np.abs(h5_main) model =", "(NMF) # =========================================== # # NMF, or non-negative matrix factorization,", "1. Singular Value Decomposition (SVD) # ===================================== # # SVD", "position in a two # dimensional grid of spatial locations.", "pycroscopy data format. # # Fortunately, all statistical analysis, machine", "a Jupyter Notebook (button at the bottom of the page)", "the resultant eigenvectors are sorted in descending # order of", "Analysis Software Prerequisites: ======================= * Standard distribution of **Anaconda** (includes", "descending order # * U - corresponding abundance maps #", "applied to complex-valued datasets, NMF only works on non-negative datasets.", "Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0,", "are not physical. # Thus, one would need to restructure", "GitHub project page by default. You are encouraged # to", "and the eigenvectors) # automatically.** In general, pycroscopy handles compound", "of spectral responses present in the # data. It is", "as np # The package used for creating and manipulating", "__future__ import division, print_function, absolute_import, unicode_literals # basic numeric computation:", "import pycroscopy as px except ImportError: print('pycroscopy not found. Will", "Matrix Factorization * Principal Component Analysis Software Prerequisites: ======================= *", "# Plotting and visualization: import matplotlib.pyplot as plt # for", "in the same manner of [position x spectra] in a", "* Standard distribution of **Anaconda** (includes numpy, scipy, matplotlib and", "download this document as a Jupyter Notebook (button at the", "# # Advantage of pycroscopy: # ------------------------ # Notice that", "of eigenvectors and abundance maps from # SVD requires care", "your data using the variable - data_file_path data_file_path = 'temp_um.h5'", "valued eigenvectors / endmembers as well as abundance maps. Complex", "data, and perform basic data analysis, including: ======================================================================================== * KMeans", "(kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value", "SVD is also very well suited for data cleaning through", "inputs the number of # clusters (sets) to partition the", "it's true capabilities are realized through the ability to seamlessly", "num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting", "can skip this cell and provide the path to your", "of the dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random',", "= decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s =", "number of # clusters (sets) to partition the data into.", "#') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0],", "def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for", "* V - Eigenvectors sorted by variance in descending order", "seamlessly perform these analyses on any imaging dataset (regardless of", "to one, we need to reshape the abundance maps: abun_maps", "px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v =", "order of variance or importance. Furthermore, SVD is also very", "datasets everywhere possible # # Furthermore, while it is not", "data that is # formatted in the same manner of", "Oak Ridge National Laboratory, Oak Ridge TN 37831, USA In", "# ======== # # In this example, we will work", "maps # * S - Variance or importance of each", "also writes back the results from SVD back to #", "accordance with the pycroscopy data format. # # Fortunately, all", "size, complexity) and storing the results back into the same", "only accept data that is # formatted in the same", "pycroscopy: try: import pycroscopy as px except ImportError: print('pycroscopy not", "# finally import pycroscopy: try: import pycroscopy as px except", "data, you can skip this cell and provide the path", "ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u", "TN 37831, USA In this notebook we load some spectral", "in the dataset since the resultant eigenvectors are sorted in", "'V'}) # Extracting the X axis - vector of frequencies", "well suited for data cleaning through # the reconstruction of", "2. KMeans Clustering # ==================== # # KMeans clustering is", "below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD", "1.0], fontsize=12) ##################################################################################### # Close and delete the h5_file h5_file.close()", "a reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main,", "variance in descending order # * U - corresponding abundance", "of [position x spectra] in a two dimensional matrix. #", "# # * V - Eigenvectors sorted by variance in", "= h5_file['Measurement_000'] # Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp,", "px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2.", "notebook we load some spectral data, and perform basic data", "the bottom of the page) and use your own data", "One solution is to stack the real value followed by", "amplitude component of the spectral data num_comps = 4 #", "of clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters))", "dataset (regardless of origin, size, complexity) and storing the results", "resultant eigenvectors are sorted in descending # order of variance", "pip.') import pip install('pycroscopy') import pycroscopy as px from pycroscopy.viz", "Notice that we are working with a complex valued dataset.", "freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape)", "in a two # dimensional grid of spatial locations. Thus,", "same dataset among other things \"\"\" # Import packages #", "one would need to restructure the data such that it", "dataset data_mat = np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat)", "data file available on our GitHub project page by default.", "to a two # dimensional matrix in accordance with the", "and abundance maps from # SVD requires care and caution", "# Notice that we are working with a complex valued", "of the dataset using only the first N (most significant)", "and python 3 from __future__ import division, print_function, absolute_import, unicode_literals", "the exponential drop of variance with number of components') #", "this cell and provide the path to your data using", "SVD. # After SVD, the real-valued eigenvectors would need to", "dimensions (x, y) have been collapsed to one, we need", "import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) #", "suited for data cleaning through # the reconstruction of the", "on both python 2 and python 3 from __future__ import", "h5_meas_grp = h5_file['Measurement_000'] # Extracting some basic parameters: num_rows =", "Getting a reference to the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data'])", "##################################################################################### # 2. KMeans Clustering # ==================== # # KMeans", "learn) * **pycroscopy** : Though pycroscopy is mainly used here", "# Extracting some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols", "==================== # # KMeans clustering is a quick and easy", "px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of", "h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] #", "valued eigenvectors. # # **Pycroscopy handles all these data transformations", "the eigenvectors would need to be restructured to get back", "SVD and k-Means that can be applied to complex-valued datasets,", ": Though pycroscopy is mainly used here for plotting purposes", "of # factors (matrices) W and H, given a matrix", "basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols')", "working with a complex valued dataset. Passing the complex values", ":25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True,", "import NMF import subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\",", "# components. So, the eigenvectors would need to be restructured", "transformations (both for the source dataset and the eigenvectors) #", "is real-valued only. # # One solution is to stack", "that it is real-valued only. # # One solution is", "# Since the two spatial dimensions (x, y) have been", "x spectra] in a two dimensional matrix. # # We", "'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to", "= h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative", "in this example, pycroscopy also writes back the results from", "stack the real value followed by the magnitude of the", "been flattened to a two # dimensional matrix in accordance", "to seamlessly perform these analyses on any imaging dataset (regardless", "ability to seamlessly perform these analyses on any imaging dataset", "num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno',", "squares is minimized. # # Set the number of clusters", "well as abundance maps. Complex valued abundance maps are not", "a two dimensional matrix. # # We will be using", "package]) # Package for downloading online files: # finally import", "- Eigenvectors sorted by variance in descending order # *", "datasets. # For illustrative purposes, we will only take the", "spectral data num_comps = 4 # get the non-negative portion", "plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12)", "get back the complex valued eigenvectors. # # **Pycroscopy handles", "subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package]) # Package for downloading online", "Matrix Factorization (NMF) # =========================================== # # NMF, or non-negative", "Ridge National Laboratory, Oak Ridge TN 37831, USA In this", "# the same source h5 file including all relevant links", "Though pycroscopy is mainly used here for plotting purposes only,", "followed by the magnitude of the imaginary component before passing", "Factorization (NMF) # =========================================== # # NMF, or non-negative matrix", "wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data", "this example, pycroscopy also writes back the results from SVD", "dataset, a spectra was collected for each position in a", "# # SVD results in three matrices: # # *", "'Amplitude (a.u.)' ##################################################################################### # 1. Singular Value Decomposition (SVD) #", "Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ==================== #", "5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label,", "by default. You are encouraged # to download this document", "of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) *", "clusters below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp", "for plotting purposes only, it's true capabilities are realized through", "pycroscopy as px except ImportError: print('pycroscopy not found. Will install", "manner of [position x spectra] in a two dimensional matrix.", "some basic parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp,", "https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that can be", "is # formatted in the same manner of [position x", "this example, we will work on a **Band Excitation Piezoresponse", "load some spectral data, and perform basic data analysis, including:", "it is real-valued only. # # One solution is to", "files: # finally import pycroscopy: try: import pycroscopy as px", "# data. It only works on data with positive real", "Fortunately, all statistical analysis, machine learning, spectral unmixing algorithms, etc.", "an data file available on our GitHub project page by", "abundance maps from # SVD requires care and caution in", "shown below # # .. image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike", "in # complex valued eigenvectors / endmembers as well as", "component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop of variance with number", "of # clusters (sets) to partition the data into. The", "document as a Jupyter Notebook (button at the bottom of", "provide the path to your data using the variable -", "dataset using only the first N (most significant) components. #", "file including all relevant links to the source dataset and", "dataset among other things \"\"\" # Import packages # Ensure", "Since the two spatial dimensions (x, y) have been collapsed", "<gh_stars>0 \"\"\" ================================================================= Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> *", "h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two", "and use your own data instead. # When using your", "The Data # ======== # # In this example, we", "pycroscopy also writes back the results from SVD back to", "plotting purposes only, it's true capabilities are realized through the", "SVD requires care and caution in interpretation. Nonetheless, it is", "acquired from advanced atomic force microscopes. In this dataset, a", "our GitHub project page by default. You are encouraged #", "cmap='inferno', title_yoffset=0.95) # Visualize the variance / statistical importance of", "h5_kmeans_grp = estimator.compute(h5_main) h5_kmeans_labels = h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp)", "Will install with pip.') import pip install('pycroscopy') import pycroscopy as", "file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------') h5_meas_grp = h5_file['Measurement_000'] # Extracting some", "is an eigenvector decomposition that is defined statistically, and therefore", "by the magnitude of the imaginary component before passing to", "or importance of each of these components # # Advantage", "Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url, data_file_path, bar=None) h5_file", "to partition the data into. The algorithm proceeds to find", "# download the data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5'", "=========================================== # # NMF, or non-negative matrix factorization, is a", "illustrative purposes, we will only take the amplitude component of", "numpy as np # The package used for creating and", "except ImportError: print('pycroscopy not found. Will install with pip.') import", "Ensure that this code works on both python 2 and", "spectra was collected for each position in a two #", "matrix in accordance with the pycroscopy data format. # #", "components # # Advantage of pycroscopy: # ------------------------ # Notice", "Thus, this is a three dimensional dataset that has been", "is a three dimensional dataset that has been flattened to", "corresponding abundance maps # * S - Variance or importance", "pycroscopy: # ------------------------ # Notice that we are working with", "a three dimensional dataset that has been flattened to a", "good method for quickly # visualizing the major trends in", "discussed in this example, pycroscopy also writes back the results", "downloading files: import wget import os # multivariate analysis: from", "px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a reference to the main dataset:", "can be applied to complex-valued datasets, NMF only works on", "# # We will be using an data file available", "# After SVD, the real-valued eigenvectors would need to be", "# SVD results in three matrices: # # * V", "produces # non-physical eigenvectors. Consequently, the interpretation of eigenvectors and", "scipy, matplotlib and sci-kit learn) * **pycroscopy** : Though pycroscopy", "a spectra was collected for each position in a two", "data format. # # Fortunately, all statistical analysis, machine learning,", "Package for downloading online files: # finally import pycroscopy: try:", "frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value) * 1E-3", "the pycroscopy data format. # # Fortunately, all statistical analysis,", "1E-3 print('Data currently of shape:', h5_main.shape) x_label = 'Frequency (kHz)'", "flattened to a two # dimensional matrix in accordance with", "= wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of", "through # the reconstruction of the dataset using only the", "try: import pycroscopy as px except ImportError: print('pycroscopy not found.", "h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s", "statistical importance of each component: px.plot_utils.plot_scree(h5_s, title='Note the exponential drop", "handles compound / complex valued datasets everywhere possible # #", "parameters: num_rows = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') #", "and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group =", "data with positive real values. It operates by approximate determination", "the amplitude component of the spectral data num_comps = 4", "a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging dataset #", "h5py # Plotting and visualization: import matplotlib.pyplot as plt #", "(both for the source dataset and the eigenvectors) # automatically.**", "# **Pycroscopy handles all these data transformations (both for the", "maps from # SVD requires care and caution in interpretation.", "* Institute for Functional Imaging of Materials * Center for", "instead. # When using your own data, you can skip", "automatically.** In general, pycroscopy handles compound / complex valued datasets", "y_label=y_label, title='SVD Eigenvectors', evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering #", "# # Unlike SVD and k-Means that can be applied", "finally import pycroscopy: try: import pycroscopy as px except ImportError:", "dataset that has been flattened to a two # dimensional", "# Thus, one would need to restructure the data such", "import os # multivariate analysis: from sklearn.cluster import KMeans from", "label_prefix='NMF Component #') axis.set_xlabel(x_label, fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14)", "we will only take the amplitude component of the spectral", "fontsize=12) ##################################################################################### # Close and delete the h5_file h5_file.close() os.remove(data_file_path)", "import h5py # Plotting and visualization: import matplotlib.pyplot as plt", "Piezoresponse Force Microscopy (BE-PFM)** imaging dataset # acquired from advanced", "'Deflection', 'units': 'V'}) # Extracting the X axis - vector", "dataset # acquired from advanced atomic force microscopes. In this", "= px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_rows') num_cols = px.hdf_utils.get_attr(h5_meas_grp, 'grid_num_cols') # Getting a", "- corresponding abundance maps # * S - Variance or", "data_file_path = wget.download(url, data_file_path, bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents", "- Variance or importance of each of these components #", "using only the first N (most significant) components. # #", "# Visualize the variance / statistical importance of each component:", "# (ie., assignment of each spectra as belonging to the", "a decomposition method, but a basic clustering method. The user", "h5_kmeans_grp['Labels'] h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response'] cluster_utils.plot_cluster_h5_group(h5_kmeans_grp) ##################################################################################### # 3. Non-negative Matrix", "data. It is not a decomposition method, but a basic", "eigenvectors / endmembers as well as abundance maps. Complex valued", "the same source h5 file including all relevant links to", "a basic clustering method. The user inputs the number of", "# Extracting the X axis - vector of frequencies h5_spec_vals", "the complex valued eigenvectors. # # **Pycroscopy handles all these", "matrix factorization, is a method that is useful towards unmixing", "In this notebook we load some spectral data, and perform", "imaging dataset (regardless of origin, size, complexity) and storing the", "that has been flattened to a two # dimensional matrix", "wget import os # multivariate analysis: from sklearn.cluster import KMeans", "the imaginary component before passing to SVD. # After SVD,", "-1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD Abundance Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95)", "is useful towards unmixing of spectral # data. It only", "For illustrative purposes, we will only take the amplitude component", "NMF, or non-negative matrix factorization, is a method that is", "eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps from", "= NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis = plt.subplots(figsize=(5.5, 5))", "================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional Imaging of", "pycroscopy.viz import cluster_utils ##################################################################################### # The Data # ======== #", "three matrices: # # * V - Eigenvectors sorted by", "KMeans Clustering # ==================== # # KMeans clustering is a", "in descending # order of variance or importance. Furthermore, SVD", "drop of variance with number of components') # Visualize the", "Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label, title='SVD", "evenly_spaced=False) ##################################################################################### # 2. KMeans Clustering # ==================== # #", "the k<sup>th</sup> set) such that the within-cluster # sum of", "the main dataset: h5_main = px.PycroDataset(h5_meas_grp['Channel_000/Raw_Data']) px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units':", "It is not a decomposition method, but a basic clustering", "x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' ##################################################################################### #", "num_components=100) h5_svd_group = decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V']", "\"\"\" # Import packages # Ensure that this code works", "= np.squeeze(h5_spec_vals.value) * 1E-3 print('Data currently of shape:', h5_main.shape) x_label", "it is not discussed in this example, pycroscopy also writes", "statistically, and therefore typically produces # non-physical eigenvectors. Consequently, the", "px.hdf_utils.write_simple_attrs(h5_main, {'quantity': 'Deflection', 'units': 'V'}) # Extracting the X axis", "get the non-negative portion of the dataset data_mat = np.abs(h5_main)", "# Visualize the eigenvectors: _ = px.plot_utils.plot_complex_spectra(h5_v[:9, :], x_label=x_label, y_label=y_label,", "Visualize the variance / statistical importance of each component: px.plot_utils.plot_scree(h5_s,", "from __future__ import division, print_function, absolute_import, unicode_literals # basic numeric", "cell and provide the path to your data using the", "belonging to the k<sup>th</sup> set) such that the within-cluster #", "image:: https://upload.wikimedia.org/wikipedia/commons/f/f9/NMF.png # # Unlike SVD and k-Means that can", "Notebook (button at the bottom of the page) and use", "pycroscopy is mainly used here for plotting purposes only, it's", "# dimensional matrix in accordance with the pycroscopy data format.", "other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute()", "# ===================================== # # SVD is an eigenvector decomposition that", "back the results from SVD back to # the same", "decomposer.compute() h5_u = h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S']", "the concatenation of the real and imaginary # components. So,", "and sci-kit learn) * **pycroscopy** : Though pycroscopy is mainly", "of origin, size, complexity) and storing the results back into", "abundance maps are not physical. # Thus, one would need", "* 1E-3 print('Data currently of shape:', h5_main.shape) x_label = 'Frequency", "restructure the data such that it is real-valued only. #", "method, but a basic clustering method. The user inputs the", "data file from Github: url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5' data_file_path = wget.download(url,", "would result in # complex valued eigenvectors / endmembers as", "not discussed in this example, pycroscopy also writes back the", "treated as the concatenation of the real and imaginary #", "for Functional Imaging of Materials * Center for Nanophase Materials", "fig, axis = plt.subplots(figsize=(5.5, 5)) px.plot_utils.plot_line_family(axis, freq_vec, model.components_, label_prefix='NMF Component", "would need to restructure the data such that it is", "other things \"\"\" # Import packages # Ensure that this", "Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) ##################################################################################### # Close and delete", "fontsize=12) axis.set_ylabel(y_label, fontsize=12) axis.set_title('NMF Components', fontsize=14) axis.legend(bbox_to_anchor=[1.0, 1.0], fontsize=12) #####################################################################################", "exponential drop of variance with number of components') # Visualize", "Non-negative Matrix Factorization (NMF) # =========================================== # # NMF, or", "is mainly used here for plotting purposes only, it's true", "print_function, absolute_import, unicode_literals # basic numeric computation: import numpy as", "only works on data with positive real values. It operates", "some spectral data, and perform basic data analysis, including: ========================================================================================", "##################################################################################### # The Data # ======== # # In this", "and manipulating HDF5 files: import h5py # Plotting and visualization:", "and perform basic data analysis, including: ======================================================================================== * KMeans Clustering", "including: ======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization *", "= h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------') px.hdf_utils.print_tree(h5_file) print('----------------------')", "/ endmembers as well as abundance maps. Complex valued abundance", "# acquired from advanced atomic force microscopes. In this dataset,", "solution is to stack the real value followed by the", "'temp_um.h5' # download the data file from Github: url =", "to reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows,", "spectral responses present in the # data. It is not", "capabilities are realized through the ability to seamlessly perform these", "only works on non-negative datasets. # For illustrative purposes, we", "Spectral Unmixing ================================================================= <NAME>, <NAME>, <NAME> * Institute for Functional", "import pycroscopy as px from pycroscopy.viz import cluster_utils ##################################################################################### #", "<NAME> * Institute for Functional Imaging of Materials * Center", "# for downloading files: import wget import os # multivariate", "Consequently, the interpretation of eigenvectors and abundance maps from #", "# 2. KMeans Clustering # ==================== # # KMeans clustering", "H, given a matrix V, as shown below # #", "Oak Ridge TN 37831, USA In this notebook we load", "data. It only works on data with positive real values.", "Microscopy (BE-PFM)** imaging dataset # acquired from advanced atomic force", "the reconstruction of the dataset using only the first N", "Unlike SVD and k-Means that can be applied to complex-valued", "very well suited for data cleaning through # the reconstruction", "computation: import numpy as np # The package used for", "work on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)** imaging", "in accordance with the pycroscopy data format. # # Fortunately,", "# automatically.** In general, pycroscopy handles compound / complex valued", "or importance. Furthermore, SVD is also very well suited for", "vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main, 'Spectroscopic_Values')[-1] freq_vec = np.squeeze(h5_spec_vals.value)", "datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100) h5_svd_group = decomposer.compute() h5_u =", "In this example, we will work on a **Band Excitation", "the X axis - vector of frequencies h5_spec_vals = px.hdf_utils.get_auxiliary_datasets(h5_main,", "the eigenvectors) # automatically.** In general, pycroscopy handles compound /", "h5_s = h5_svd_group['S'] # Since the two spatial dimensions (x,", "real value followed by the magnitude of the imaginary component", "as is to SVD would result in # complex valued", "abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9, title='SVD", "proceeds to find the optimal labeling # (ie., assignment of", "# visualizing the major trends in the dataset since the", "into. The algorithm proceeds to find the optimal labeling #", "# to download this document as a Jupyter Notebook (button", "of the real and imaginary # components. So, the eigenvectors", "##################################################################################### # 3. Non-negative Matrix Factorization (NMF) # =========================================== #", "# data. It is not a decomposition method, but a", "from pycroscopy.viz import cluster_utils ##################################################################################### # The Data # ========", "import division, print_function, absolute_import, unicode_literals # basic numeric computation: import", "component before passing to SVD. # After SVD, the real-valued", "Variance or importance of each of these components # #", "maps: abun_maps = np.reshape(h5_u[:, :25], (num_rows, num_cols, -1)) px.plot_utils.plot_map_stack(abun_maps, num_comps=9,", "the source dataset and the eigenvectors) # automatically.** In general,", "Force Microscopy (BE-PFM)** imaging dataset # acquired from advanced atomic", "is a quick and easy method to determine the types", "easy method to determine the types of spectral responses present", "same manner of [position x spectra] in a two dimensional", "the number of clusters below num_clusters = 4 estimator =", "cleaning through # the reconstruction of the dataset using only", "Factorization * Principal Component Analysis Software Prerequisites: ======================= * Standard", "Singular Value Decomposition (SVD) # ===================================== # # SVD is", "source dataset and other ancillary datasets decomposer = px.processing.svd_utils.SVD(h5_main, num_components=100)", "useful towards unmixing of spectral # data. It only works", "import matplotlib.pyplot as plt # for downloading files: import wget", "the data such that it is real-valued only. # #", "that is # formatted in the same manner of [position", "= 'temp_um.h5' # download the data file from Github: url", "Maps', reverse_dims=True, color_bar_mode='single', cmap='inferno', title_yoffset=0.95) # Visualize the variance /", "present in the # data. It is not a decomposition", "two spatial dimensions (x, y) have been collapsed to one,", "from sklearn.decomposition import NMF import subprocess import sys def install(package):", "these analyses on any imaging dataset (regardless of origin, size,", "possible # # Furthermore, while it is not discussed in", "labeling # (ie., assignment of each spectra as belonging to", "below num_clusters = 4 estimator = px.processing.Cluster(h5_main, KMeans(n_clusters=num_clusters)) h5_kmeans_grp =", "of variance with number of components') # Visualize the eigenvectors:", "======================================================================================== * KMeans Clustering * Non-negative Matrix Factorization * Principal", "h5_main.shape) x_label = 'Frequency (kHz)' y_label = 'Amplitude (a.u.)' #####################################################################################", "python 2 and python 3 from __future__ import division, print_function,", "the # data. It is not a decomposition method, but", "Center for Nanophase Materials Sciences Oak Ridge National Laboratory, Oak", "SVD is an eigenvector decomposition that is defined statistically, and", "of the spectral data num_comps = 4 # get the", "any imaging dataset (regardless of origin, size, complexity) and storing", "# get the non-negative portion of the dataset data_mat =", "np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis =", "(includes numpy, scipy, matplotlib and sci-kit learn) * **pycroscopy** :", "the interpretation of eigenvectors and abundance maps from # SVD", "will work on a **Band Excitation Piezoresponse Force Microscopy (BE-PFM)**", "of each spectra as belonging to the k<sup>th</sup> set) such", "results back into the same dataset among other things \"\"\"", "this dataset, a spectra was collected for each position in", "SVD would result in # complex valued eigenvectors / endmembers", "complex valued dataset. Passing the complex values as is to", "general, pycroscopy handles compound / complex valued datasets everywhere possible", "= h5_svd_group['U'] h5_v = h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since", "subprocess import sys def install(package): subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", package])", "The user inputs the number of # clusters (sets) to", "eigenvectors would need to be restructured to get back the", "including all relevant links to the source dataset and other", "encouraged # to download this document as a Jupyter Notebook", "# When using your own data, you can skip this", "atomic force microscopes. In this dataset, a spectra was collected", "the results from SVD back to # the same source", "= np.abs(h5_main) model = NMF(n_components=num_comps, init='random', random_state=0) model.fit(data_mat) fig, axis", "for Nanophase Materials Sciences Oak Ridge National Laboratory, Oak Ridge", "a two # dimensional matrix in accordance with the pycroscopy", "------------------------ # Notice that we are working with a complex", "of pycroscopy: # ------------------------ # Notice that we are working", "bar=None) h5_file = h5py.File(data_file_path, mode='r+') print('Contents of data file:') print('----------------------')", "be treated as the concatenation of the real and imaginary", "from sklearn.cluster import KMeans from sklearn.decomposition import NMF import subprocess", "# 3. Non-negative Matrix Factorization (NMF) # =========================================== # #", "purposes, we will only take the amplitude component of the", "origin, size, complexity) and storing the results back into the", "imaging dataset # acquired from advanced atomic force microscopes. In", "# sum of squares is minimized. # # Set the", "h5_svd_group['V'] h5_s = h5_svd_group['S'] # Since the two spatial dimensions", "a quick and easy method to determine the types of", "and storing the results back into the same dataset among", "SVD results in three matrices: # # * V -", "need to reshape the abundance maps: abun_maps = np.reshape(h5_u[:, :25],", "clustering method. The user inputs the number of # clusters", "that is defined statistically, and therefore typically produces # non-physical" ]
[ "self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response =", "test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def", "shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock()", "self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen):", "mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context", "= 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url", "'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self):", "= 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url", "import Path from unittest import TestCase from unittest.mock import Mock", "'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self,", "url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context']", "url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self):", "get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt'", "import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url", "patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from", "(Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True)", "{}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File", "b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url)", "context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to)", "with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen',", "f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url =", "unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile import", "content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url,", "import TestCase from unittest.mock import Mock from unittest.mock import patch", "content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value", "= 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request =", "= 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url", "download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {})", "= get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext", "class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True)", "def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile')", "get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve()", "urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f:", "with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen',", "TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def", "= (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen',", "unittest.mock import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile import", "self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content')", "test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value", "self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url)", "def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt')", "/ 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def", "url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {})", "= mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0]", "name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar'", "ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile'", "ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value", "Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url =", "'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock()", "content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt'", "open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True)", "def setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self):", "urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f:", "Path from unittest import TestCase from unittest.mock import Mock from", "'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url =", "get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext =", "'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name,", "get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext =", "def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '')", "test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class", "= get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name", "test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def", "url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context =", "urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value =", "ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar'", "'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0]", "def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response", "download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class", "/ 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def", "= get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name", "from unittest.mock import Mock from unittest.mock import patch from foliant.config.downloadfile", "name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile'", "self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext", "test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value", "= get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext", "self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True)", "from foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile", "urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request =", "@patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value =", "from unittest import TestCase from unittest.mock import Mock from unittest.mock", "import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self):", "self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(),", "as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen):", "url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def test_no_ext(self):", "Mock from unittest.mock import patch from foliant.config.downloadfile import download_file from", "autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File", "foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent", "= urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir", "'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name", "'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name,", "self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(),", "url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self):", "self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content')", "open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase):", "def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt')", "request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with", "content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request", "urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir /", "self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response =", "urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as f:", "= b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(", "as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url", "def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content'", "'') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext = get_file_ext_from_url(url) self.assertEqual(ext,", "= urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as", "download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers,", "save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self,", "save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context)", "import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url", "from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase):", "def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt')", "= 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def", "get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name =", "= 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url", "f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response", "TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name,", "pathlib import Path from unittest import TestCase from unittest.mock import", "from pathlib import Path from unittest import TestCase from unittest.mock", "self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt'", "save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context", "@patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value =", "content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value", "def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt')", "b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir,", "url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase):", "'.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext,", "tearDown(self): shutil.rmtree(self.project_dir, ignore_errors=True) @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_only_url(self, urlopen): mock_response =", "mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt'", "f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response", "urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir,", "= urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir", "with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class", "= b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir,", "mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to)", "def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content'", "self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(),", "'myfile.txt') as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self,", "login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization',", "url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request", "urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john',", "get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name =", "from unittest.mock import patch from foliant.config.downloadfile import download_file from foliant.config.downloadfile", "unittest import TestCase from unittest.mock import Mock from unittest.mock import", "= mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>'", "TestCase from unittest.mock import Mock from unittest.mock import patch from", "context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt')", "import shutil from pathlib import Path from unittest import TestCase", "test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext, '.txt') def", "mock_response url = 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' )", "= urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as", "open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True)", "'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_with_auth(self, urlopen): mock_response = Mock()", ") request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context)", "urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir /", "/ 'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def", "'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers,", "url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context)", "mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response", "self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url)", "TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url) self.assertEqual(ext,", "content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name =", "'myfile.txt') as f: self.assertEqual(f.read(), 'File content') class TestGetFileNameFromURL(TestCase): def test_with_ext(self):", "url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request", "test_no_ext(self): url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def", "'http://example.com/sub/myfile' ext = get_file_ext_from_url(url) self.assertEqual(ext, '') def test_with_clutter(self): url =", "url = 'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self):", "foliant.config.downloadfile import download_file from foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import", "class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext = get_file_ext_from_url(url)", "= b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to", "= 'http://example.com/myfile.txt' download_file(root_dir=self.project_dir, url=url) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context']", "@patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen): mock_response = Mock() mock_response.read.return_value =", "autospec=True) def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File", "/ save_to) as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def", "= 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context =", "request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt') as f: self.assertEqual(f.read(), 'File", "= mock_response url = 'http://example.com/myfile.txt' save_to = 'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url,", "class TestGetFileNameFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url)", "b'File content' urlopen.return_value = mock_response url = 'http://example.com/myfile.txt' save_to =", "password='<PASSWORD>' ) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers)", "foliant.config.downloadfile import get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def", "from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir =", "as f: self.assertEqual(f.read(), 'File content') @patch('foliant.config.downloadfile.urlopen', autospec=True) def test_save_to(self, urlopen):", "= get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url =", "'subdir1/subdir2/downloaded.txt' download_file(root_dir=self.project_dir, url=url, save_to=save_to) request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context']", "'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url = 'http://example.com/sub/myfile.txt' ext =", "'http://example.com/sub/myfile' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile') def test_with_clutter(self): url =", "context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with open(self.project_dir / 'myfile.txt')", "get_file_ext_from_url from foliant.config.downloadfile import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir", "import get_file_name_from_url class TestDownloadFile(TestCase): def setUp(self): self.project_dir = (Path(__file__).parent /", "{}) self.assertIsNone(context) with open(self.project_dir / save_to) as f: self.assertEqual(f.read(), 'File", "'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0]", "shutil from pathlib import Path from unittest import TestCase from", "def test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content'", "root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context =", "'http://example.com/sub/myfile.txt' name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') def test_no_ext(self): url =", "= urlopen.call_args.kwargs['context'] self.assertEqual(request.headers, {}) self.assertIsNone(context) with open(self.project_dir / save_to) as", "name = get_file_name_from_url(url) self.assertEqual(name, 'myfile.txt') class TestGetFileExtFromURL(TestCase): def test_with_ext(self): url", "test_with_auth(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File content' urlopen.return_value", "setUp(self): self.project_dir = (Path(__file__).parent / 'project_dir').resolve() self.project_dir.mkdir(exist_ok=True) def tearDown(self): shutil.rmtree(self.project_dir,", "= Mock() mock_response.read.return_value = b'File content' urlopen.return_value = mock_response url", "autospec=True) def test_only_url(self, urlopen): mock_response = Mock() mock_response.read.return_value = b'File", "= 'http://example.com/myfile.txt' download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request =", "import Mock from unittest.mock import patch from foliant.config.downloadfile import download_file", "download_file( root_dir=self.project_dir, url=url, login='john', password='<PASSWORD>' ) request = urlopen.call_args.args[0] context", "self.assertEqual(ext, '') def test_with_clutter(self): url = 'http://example.com/sub/myfile.txt?param=val&foo=bar' ext = get_file_ext_from_url(url)", "request = urlopen.call_args.args[0] context = urlopen.call_args.kwargs['context'] self.assertIn('Authorization', request.headers) self.assertIsNone(context) with", "self.assertEqual(ext, '.txt') def test_no_ext(self): url = 'http://example.com/sub/myfile' ext = get_file_ext_from_url(url)" ]
[ "# 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() #", "# 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定", "# 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in", "positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id']", "await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】'", "message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id =", "= client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす", "ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id':", "idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm() #", "# 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) #", "target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id'] # botとしてDiscordに接続(botのトークンを指定) client.run('605042341715378176')", "for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name:", "@client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def", "= message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM #", "question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await", "指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel", "711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧", "target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) #", "> int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す", "<gh_stars>0 import discord client = discord.Client() # 接続に使用するオブジェクト # 起動時", "# チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す", "匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得", "# カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels", "カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels =", "client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if", "質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else:", "# id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm =", "on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip()", "*********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name =", "指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name #", "0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry,", "getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm", "target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] >", "# 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} # ***********************************************************", "print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if", "-> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999}", "= await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n'", "メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): #", "# 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question)", "+ question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信", "= discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready():", "# 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event", "接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視", "def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): #", "0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396", "# *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for", "channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: #", "int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return", "繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] =", "if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id", "discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功')", "async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question", "文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() #", "質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id", "target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成 await", "dm = await message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.'", "if target_channel_id == 0: dm = await message.author.create_dm() # 質問者へDM作成", "= 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # *********************************************************** #", "*********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel", "target_channel = {'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前", "import discord client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event", "起動時 @client.event async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async", "匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: #", "await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId()", "# idが0以外なら匿名質問する if target_channel_id == 0: dm = await message.author.create_dm()", "message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する", "= {'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id", "99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定", "client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす #", "= client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす", "# *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name", "on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする", "{'id': 0, 'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id =", "all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: #", "全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) ==", "# 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル)", "target_category_name = client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels", "str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if", "# 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId()", "else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question)", "if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる", "指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels:", "# メッセージを監視 @client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'):", "メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel =", "# ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel =", "# 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] =", "question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM", "質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} # *********************************************************** #", "if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position)", "# 接続に使用するオブジェクト # 起動時 @client.event async def on_ready(): print('ログイン成功') #", "await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: #", "指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 #", "== 0: dm = await message.author.create_dm() # 質問者へDM作成 await dm.send(", "「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question = message.content[len('/box'):].strip() # 質問させたいチャンネルのid", "discord client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async", "'position': 99999999} # *********************************************************** # 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 #", "# 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id) target_channel['position']", "message.author.create_dm() # 質問者へDM作成 await dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' +", "int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position': 99999999} #", "= int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id'] #", "int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id'] # botとしてDiscordに接続(botのトークンを指定)", "client = discord.Client() # 接続に使用するオブジェクト # 起動時 @client.event async def", "dm.send( 'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル", "def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く question =", "# 質問させたいチャンネルのid target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if", "= getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0:", "target_channel_id = getTargetChannelId() # id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id ==", "getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0, 'position':", "'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id)", "# 指定カテゴリ(対象チャンネルが含まれたカテゴリ)の名前 category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name", "'Sorry, メッセージを送信できませんでした.' 'もう1度試してみてください.\\n' '【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel", "# positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position):", "初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position'] > int(channel.position): target_channel['id'] = int(channel.id)", "client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels # 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す", "id=0なら質問者にエラー報告DM # idが0以外なら匿名質問する if target_channel_id == 0: dm = await", "'【質問文】' + question) else: # 匿名質問させたいチャンネル target_channel = client.get_channel(target_channel_id) #", "category_id = 711238137598181396 # カテゴリidを指定 target_category_name = client.get_channel(category_id).name # ***********************************************************", "== target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 # 初期値はpositionが大きい(99999999)ので,必ず入れ替わる想定 # 繰り返せば,最後にはpositionが最も小さいチャンネルを代入できる if target_channel['position']", "チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def", "# 全てのTextチャンネルから「指定カテゴリに属する最初のチャンネル」を探す for channel in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category)", "def getTargetChannelId() -> int: # 質問させたいチャンネル(対象チャンネル) target_channel = {'id': 0,", "= client.get_channel(category_id).name # *********************************************************** # 指定したサーバにある全てのTextチャンネル一覧 all_channels = client.get_guild(602423784946925568).text_channels #", "all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換 #", "target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() ->", "target_channel = client.get_channel(target_channel_id) # チャンネルに質問メッセージ送信 await target_channel.send(question) # 匿名質問させたいチャンネルのidを取得 #", "in all_channels: # 指定カテゴリに属する場合だけ対象チャンネル候補とみなす if str(channel.category) == target_category_name: # positionが小さいほうを「より対象チャンネルに近い」として交換", "# 匿名質問させたいチャンネルのidを取得 # 指定したカテゴリにある最初のTextチャンネル=質問させたいチャンネルとみなす # ただしカテゴリにチャンネルが無い時は0を返す def getTargetChannelId() -> int:", "@client.event async def on_message(message): # 「/box」が頭についたメッセージならオウム返しする if message.content.startswith('/box'): # 文字から「/box」を抜く", "async def on_ready(): print('ログイン成功') # メッセージを監視 @client.event async def on_message(message):", "target_channel['id'] = int(channel.id) target_channel['position'] = int(channel.position) # 最終的に代入されたidを返す return target_channel['id']" ]
[ "= np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse", "exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop =", "= exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop", "exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax =", "None: counts_total = data else: counts_total += data # data", "# check to see if any genotypes are at least", "suffix = '07212021_0001' data_folder = 'results_' + suffix exp_info_file =", "+ suffix exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info", "os.sep + sim data = results_manager.get_data(sim) dc = data[:,-1] data", "plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 )", "drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t =", "data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12,", "counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg)", "($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs,", "0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:]", "True data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black',", "# counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num],", "pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[]", "sim_files: sim = sim_files[k] sim = exp + os.sep +", "sim in sim_files: sim = sim_files[k] sim = exp +", "exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs", "k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' }", "t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append(", "os suffix = '07212021_0001' data_folder = 'results_' + suffix exp_info_file", "exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num", "tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0", "tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t", "grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1", "plt import numpy as np from fears.utils import results_manager, plotter,", "counts_total is None: counts_total = data else: counts_total += data", "} tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False,", "color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if", "for exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t)", "linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da", "in sim_files: sim = sim_files[k] sim = exp + os.sep", "sim = sim_files[k] sim = exp + os.sep + sim", "color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else:", "least 10% of the max cell count if any(data_t >=", "np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),))", "# data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data =", "drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 )", "# da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files)", "= counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax,", "np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate timecourse axes", "= np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append( tcax", "da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count", "while k < len(sim_files): # for sim in sim_files: sim", "= exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax", "alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg", "survive_count > 0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg)", "results_manager, plotter, dir_manager import os suffix = '07212021_0001' data_folder =", "# data = data/np.max(data) data_t = data[-1,:] # check to", "= results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] # data", "data_folder = 'results_' + suffix exp_info_file = 'experiment_info_' + suffix", "= tcax.twinx() sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count =", "data[-1,:] # check to see if any genotypes are at", "= {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax =", "grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax )", "import results_manager, plotter, dir_manager import os suffix = '07212021_0001' data_folder", "num[0,0] # generate timecourse axes tcax = ax[axnum] # da", "= data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug", "exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for", "= 'results_' + suffix exp_info_file = 'experiment_info_' + suffix +", "sorted(sim_files) survive_count = 0 counts_total = None k=0 while k", "if any(data_t >= 1): survive_count += 1 if counts_total is", "= os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total =", "in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num =", "import numpy as np from fears.utils import results_manager, plotter, dir_manager", "np from fears.utils import results_manager, plotter, dir_manager import os suffix", "suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells", "linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count >", "plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1,", "counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) #", "tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True,", "exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder,", "labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0:", "'.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims =", "any genotypes are at least 10% of the max cell", "= data[-1,:] # check to see if any genotypes are", "exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0: drug_kwargs =", "numpy as np from fears.utils import results_manager, plotter, dir_manager import", "= plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) #", "tcax, labelsize=12) # t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24", "# drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg = counts_total/survive_count", "= counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp", "the max cell count if any(data_t >= 1): survive_count +=", "counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12)", "drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('')", "data else: counts_total += data # data = data/np.max(data) #", "for sim in sim_files: sim = sim_files[k] sim = exp", "ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp", "alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num],", "ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders:", "counts_total = data else: counts_total += data # data =", "if any genotypes are at least 10% of the max", "= sorted(sim_files) survive_count = 0 counts_total = None k=0 while", "is None: counts_total = data else: counts_total += data #", "counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp =", "counts_avg = counts_total counts_avg = counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg,", "np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append( tcax )", "drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg = counts_total/survive_count #", "== k_abs_t) num = num[0,0] # generate timecourse axes tcax", "k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax", "0 counts_total = None k=0 while k < len(sim_files): #", "data_t = data[-1,:] # check to see if any genotypes", "'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells", "{'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num],", "= exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t)", "= ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files", "sim_files = os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total", "'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax,", "counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg =", "= counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t", "of the max cell count if any(data_t >= 1): survive_count", "if counts_total is None: counts_total = data else: counts_total +=", "import os suffix = '07212021_0001' data_folder = 'results_' + suffix", "survive_count += 1 if counts_total is None: counts_total = data", "float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num = num[0,0] #", "exp in exp_folders: k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num", "max cell count if any(data_t >= 1): survive_count += 1", "+= 1 if counts_total is None: counts_total = data else:", "are at least 10% of the max cell count if", "= data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells if", "# counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg =", "< len(sim_files): # for sim in sim_files: sim = sim_files[k]", "data/np.max(data) data_t = data[-1,:] # check to see if any", ") drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data,", "exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0]", "any(data_t >= 1): survive_count += 1 if counts_total is None:", "import matplotlib.pyplot as plt import numpy as np from fears.utils", "labelsize=12) # t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 #", "else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2,", "'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data,", "drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax", "tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12,", "data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2,", "n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs)", "sim_files[k] sim = exp + os.sep + sim data =", "drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax,", "survive_count = 0 counts_total = None k=0 while k <", "# generate timecourse axes tcax = ax[axnum] # da =", "+ sim data = results_manager.get_data(sim) dc = data[:,-1] data =", "= True data = data/max_cells if k==0: drug_kwargs = {'alpha':0.7,", "to see if any genotypes are at least 10% of", "generate timecourse axes tcax = ax[axnum] # da = tcax.twinx()", "counts_total = None k=0 while k < len(sim_files): # for", "see if any genotypes are at least 10% of the", "sim data = results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1]", "from fears.utils import results_manager, plotter, dir_manager import os suffix =", "k_abs_t = float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num =", ") else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False,", "drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray',", "= plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum =", "data = results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] #", "fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum", "legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax", "1): survive_count += 1 if counts_total is None: counts_total =", "= 0 counts_total = None k=0 while k < len(sim_files):", "= 'experiment_info_' + suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file)", "cell count if any(data_t >= 1): survive_count += 1 if", "data[:,-1] data = data[:,0:-1] # data = data/np.max(data) data_t =", "dir_manager import os suffix = '07212021_0001' data_folder = 'results_' +", "= plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray',", "= '07212021_0001' data_folder = 'results_' + suffix exp_info_file = 'experiment_info_'", "10% of the max cell count if any(data_t >= 1):", "else: counts_total += data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale", "counts_total += data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale =", "= counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total", "os.listdir(path=exp) sim_files = sorted(sim_files) survive_count = 0 counts_total = None", "counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg = counts_total counts_avg", "k_abs_t) num = num[0,0] # generate timecourse axes tcax =", "= exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[]", "'results_' + suffix exp_info_file = 'experiment_info_' + suffix + '.p'", "= 0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t =", "None k=0 while k < len(sim_files): # for sim in", "k=0 while k < len(sim_files): # for sim in sim_files:", "k_abs = exp_info.slopes exp_folders.reverse() k_abs = np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4))", "+ os.sep + sim data = results_manager.get_data(sim) dc = data[:,-1]", "check to see if any genotypes are at least 10%", "0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) # counts_avg", "max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse()", "sim = exp + os.sep + sim data = results_manager.get_data(sim)", "# t = np.arange(len(dc)) # t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc)", "matplotlib.pyplot as plt import numpy as np from fears.utils import", "ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp) sim_files =", "= data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:] #", "= data else: counts_total += data # data = data/np.max(data)", "+ suffix + '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells =", "= data[:,-1] data = data[:,0:-1] # data = data/np.max(data) data_t", "num = num[0,0] # generate timecourse axes tcax = ax[axnum]", "num = np.argwhere(k_abs == k_abs_t) num = num[0,0] # generate", "tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc))", "> 0: counts_avg = counts_total/survive_count # counts_avg = counts_avg/np.max(counts_avg) #", "plotter, dir_manager import os suffix = '07212021_0001' data_folder = 'results_'", "= exp + os.sep + sim data = results_manager.get_data(sim) dc", "'07212021_0001' data_folder = 'results_' + suffix exp_info_file = 'experiment_info_' +", "= exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs", "suffix exp_info_file = 'experiment_info_' + suffix + '.p' exp_folders,exp_info =", "labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append( drug_ax ) else: tcax,da =", "k+=1 if survive_count > 0: counts_avg = counts_total/survive_count # counts_avg", "= plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2", "exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims", "data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data", "+ '.p' exp_folders,exp_info = results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims", ">= 1): survive_count += 1 if counts_total is None: counts_total", "as plt import numpy as np from fears.utils import results_manager,", "data = data/np.max(data) data_t = data[-1,:] # check to see", "if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration ($\\u03BC$M)'", "data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:] # check", "Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc, drug_ax_sci_notation=True,", ") # drug_ax.set_ylim(0,10**4) k+=1 if survive_count > 0: counts_avg =", "counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) # t =", "plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax = ax.reshape((len(k_abs),)) axnum = 0", "k_abs_t = exp[exp.find('=')+1:] k_abs_t = float(k_abs_t) num = np.argwhere(k_abs ==", "exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes", "tcax, drug_curve=dc, drug_ax_sci_notation=True, drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7", "+= data # data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True", "genotypes are at least 10% of the max cell count", "= results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs", "timecourse axes tcax = ax[axnum] # da = tcax.twinx() sim_files", "# for sim in sim_files: sim = sim_files[k] sim =", "data = data[:,0:-1] # data = data/np.max(data) data_t = data[-1,:]", "counts_avg/np.max(counts_avg) tcax,temp = plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t =", "sim_files = sorted(sim_files) survive_count = 0 counts_total = None k=0", "as np from fears.utils import results_manager, plotter, dir_manager import os", "= np.flip(k_abs) fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(4,4)) pop = exp_info.populations[0] ax =", "= data/np.max(data) data_t = data[-1,:] # check to see if", "tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4)", "data = data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells", "= ax.reshape((len(k_abs),)) axnum = 0 tc_axes=[] drug_axes=[] for exp in", "'label':'Drug Concentration ($\\u03BC$M)' } tcax,drug_ax = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, drug_curve=dc,", "drug_axes.append( drug_ax ) else: tcax,da = plotter.plot_timecourse_to_axes(exp_info.populations[num], data, tcax, grayscale=True,", "fears.utils import results_manager, plotter, dir_manager import os suffix = '07212021_0001'", "# t = t*exp_info.populations[0].timestep_scale/24 # da.plot(t,dc) tc_axes.append( tcax ) axnum+=1", "= num[0,0] # generate timecourse axes tcax = ax[axnum] #", "data/max_cells if k==0: drug_kwargs = {'alpha':0.7, 'color':'black', 'linewidth':2, 'label':'Drug Concentration", "at least 10% of the max cell count if any(data_t", "= sim_files[k] sim = exp + os.sep + sim data", "axes tcax = ax[axnum] # da = tcax.twinx() sim_files =", "dc = data[:,-1] data = data[:,0:-1] # data = data/np.max(data)", "legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) # drug_ax.set_ylim(0,10**4) k+=1 if survive_count", "# exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0: drug_kwargs", "plotter.plot_timecourse_to_axes(exp_info.populations[num], counts_avg, tcax, labelsize=12) # t = np.arange(len(dc)) # t", "drug_kwargs=drug_kwargs, legend_labels=False, grayscale=True, color='gray', linewidth=1, labelsize=12, alpha=0.7 ) drug_ax.set_ylabel('') drug_axes.append(", "count if any(data_t >= 1): survive_count += 1 if counts_total", "= None k=0 while k < len(sim_files): # for sim", "if survive_count > 0: counts_avg = counts_total/survive_count # counts_avg =", "results_manager.get_data(sim) dc = data[:,-1] data = data[:,0:-1] # data =", "tcax = ax[axnum] # da = tcax.twinx() sim_files = os.listdir(path=exp)", "axnum = 0 tc_axes=[] drug_axes=[] for exp in exp_folders: k_abs_t", "results_manager.get_experiment_results(data_folder, exp_info_file) max_cells = exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs =", "1 if counts_total is None: counts_total = data else: counts_total", "exp + os.sep + sim data = results_manager.get_data(sim) dc =", "len(sim_files): # for sim in sim_files: sim = sim_files[k] sim", "data/np.max(data) # exp_info.populations[num].counts_log_scale = True data = data/max_cells if k==0:", "= float(k_abs_t) num = np.argwhere(k_abs == k_abs_t) num = num[0,0]", "data, tcax, grayscale=True, color='gray', legend_labels=False, linewidth=2, labelsize=12, alpha=0.2 ) #", "k < len(sim_files): # for sim in sim_files: sim =", "exp_info.populations[0].max_cells n_sims = exp_info.n_sims k_abs = exp_info.slopes exp_folders.reverse() k_abs =" ]
[ "are problematic (but will hopefully be solved # later by", "s_newarg) == s_oldarg else: assert not self.frozen if block not", "that have blocked blocks # --- end of debugging information", "set of links that have ever been followed self.notify =", "map {block: graph-containing-it} self.annotated = {} # set of blocks", "block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self,", "the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the", "it should try to progress elsewhere.\"\"\" def __init__(self, annotator, op,", "immediately caught by # an exception handler. We then only", "make sure that the return variables of all graphs is", "try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self,", "self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]:", "signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if", "= '\\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged", "that the situation is currently blocked, and that it should", "rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify, transform", "return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op) __str__ = __repr__", "= True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset", "% (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation", "def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block,", "newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue)", "= False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex)", "% (pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self,", "low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg =", "(s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation =", "flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells):", "position_key): graph, block, i = position_key blk = \"\" if", "raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper)", "block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks =", "is None: newblocks = self.annotated # all of them for", "# set of graphs not to annotate again self.blocked_blocks =", "block: at = block.at() if at: blk = \" block\"+at", "hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s,", "Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self,", "saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs())", "= False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values():", "except BlockedInference as e: if e.op is block.raising_op: # this", "block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits", "operations ______ def consider_op(self, op): # let's be careful about", "pass impossible values if s_out == s_ImpossibleValue: ignore_link = True", "the initial bindings for the input args of a block.", "gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator", "def reflowpendingblock(self, graph, block): assert not self.frozen assert graph not", "%r' % (arg,)) def binding(self, arg): \"Gives the SomeValue corresponding", "s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for", "self.opindex = opindex def __repr__(self): if not self.break_at: break_at =", "done (at least until we find we must generalize the", "# Create the initial bindings for the input args of", "special case for annotating/rtyping in several phases: calling # a", "-1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert", "can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception):", "raise BlockedInference(self, op, -1) # the operation cannot succeed assert", "of the block will # always raise an exception which", "new # annotations that are passed in, and don't annotate", "Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise", "self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph,", "in newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks", "please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return", "if op.result.annotation is None: break # ignore the unannotated part", "== v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const =", "enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None),", "raise # The dict 'added_blocks' is used by rpython.annlowlevel to", "be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic", "self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] =", "e: # note that UnionError is a subclass e.source =", "== s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case)", "return value v = graph.getreturnvar() try: return self.binding(v) except KeyError:", "got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs #all", "# XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells =", "from rpython.translator import simplify, transform from rpython.annotator import model as", "done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) #", "invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy,", "try: i = 0 while i < len(block.operations): op =", "# The analysis of a block can be in three", "self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: # hack", "self.follow_link(graph, link, constraints) if block in self.notify: # reflow from", "c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add", "if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" %", "__________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations", "= s_value def warning(self, msg, pos=None): if pos is None:", "self.complete() # invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks)", "code to the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True))", "sure that the return variables of all graphs is annotated", "graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index =", "__init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at =", "= {} self.complete() # invoke annotation simplifications for the new", "rtyped. Safety-check the new # annotations that are passed in,", "graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block)", "raise TypeError(\"Variable or Constant instance expected, \" \"got %r\" %", "= True blocked_blocks = [block for block, done in self.annotated.items()", "rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator", "for debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block',", "s_constraint).improve() # ignore links that try to pass impossible values", "get the (current) return value v = graph.getreturnvar() try: return", "None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs", "self.policy = policy try: self.added_blocks = {} self.complete() # invoke", "the block have bindings but we # still have to", "point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending", "in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell", "inputcells): # Create the initial bindings for the input args", "def call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks", "= {} for link in exits: constraints = knowntypedata.get(link.exitcase, {})", "an exception. We then # swallow the BlockedInference and that's", "# XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s =", "already seen self.added_blocks = None # see processblock() below self.links_followed", "the analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def", "self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block] try:", "exception. We then # swallow the BlockedInference and that's it.", "policy try: self.added_blocks = {} self.complete() # invoke annotation simplifications", "== s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op)", "resultcell to op.result def get_exception(self, operation): \"\"\" Return the annotation", "the flow object space. These are the operations for #", "link in exits: case = link.exitcase if case is None:", "Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for", "in newgraphs: v = graph.getreturnvar() if v.annotation is None: self.setbinding(v,", "the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives", "self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph, None)", "v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type", "to the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise", "the (current) return value v = graph.getreturnvar() try: return self.binding(v)", "= [link for link in exits if link.exitcase == s_exitswitch.const]", "return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r'", "graphs is annotated if self.added_blocks is not None: newgraphs =", "elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self,", "flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return", "< len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops", "only issue calls to self.addpendingblock(). # The analysis of a", "def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy", "else: graphs = {} for block in block_subset: graph =", "self.frozen = False if policy is None: from rpython.annotator.policy import", "the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def", "the name of the call operations in sync # with", "The dict 'added_blocks' is used by rpython.annlowlevel to # detect", "# make input arguments and set their type args_s =", "not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert", "= self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph", "whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence", "absolute_import import types from collections import defaultdict from rpython.tool.ansi_print import", "reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def", "= self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try:", "below self.links_followed = {} # set of links that have", "+= renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if", "blk = \" block\"+at opid=\"\" if i is not None:", "( \"%r is not dict. please update %s.__getstate__\" % (key,", "return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals", "used by rpython.annlowlevel to # detect which are the new", "the type inference engine that the situation is currently blocked,", "ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self,", "if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits =", "block, inputcells): # Create the initial bindings for the input", "all the operations in the block. # * self.annotated[block] ==", "newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints", "s_oldarg else: assert not self.frozen if block not in self.annotated:", "setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self,", "graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy =", "graph-containing-block: # analysis done (at least until we find we", "# detect which are the new blocks that annotating an", "self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position", "perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython.", "for annotating/rtyping in several phases: calling # a graph that", "is done for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback)", "are the new blocks that annotating an additional # small", "self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation if s_old", "graph, block, inputcells): # Merge the new 'cells' with each", "None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self,", "callback = whence callpositions[callback] = True # generalize the function's", "'?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___", "in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] =", "[link for link in exits if link.exitcase == s_exitswitch.const] if", "block): try: i = 0 while i < len(block.operations): op", "graphs not to annotate again self.blocked_blocks = {} # set", "blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph,", "assert len(inputcells) == nbarg # wrong number of args #", "follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and", "= self.translator.graphs else: graphs = {} for block in block_subset:", "self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] =", "if block in self.notify: # reflow from certain positions when", "if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return", "getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for link", "is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None)", "--- the following information is recorded for debugging --- self.blocked_graphs", "= block.at() if at: blk = \" block\"+at opid=\"\" if", "is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise", "\" block\"+at opid=\"\" if i is not None: opid =", "link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if", "link, constraints) if block in self.notify: # reflow from certain", "raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note", "self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e:", "del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block]", "XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function,", "graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks", "block is done for callback in self.notify[block]: if isinstance(callback, tuple):", "resultcell is None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue:", "if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class", "self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make sure", "= v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out", "solved # later by reflowing). Throw the BlockedInference up to", "intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations", "seen self.added_blocks = None # see processblock() below self.links_followed =", "try to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator", "import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class", "fine to always raise an exception. We then # swallow", "graph) else: callback = whence callpositions[callback] = True # generalize", "self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated", "block have bindings but we # still have to consider", "block): # Important: this is not called recursively. # self.flowin()", "hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s,", "by reflowing). Throw the BlockedInference up to # processblock(). e.opindex", "from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block", "issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value,", "of the call operations in sync # with the flow", "setbinding(self, arg, s_value): s_old = arg.annotation if s_old is not", "is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): #", "is None: try: pos = self.bookkeeper.position_key except AttributeError: pos =", "not self.pendingblocks: break # finished # make sure that the", "rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper", "to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator =", "medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells)", "callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType,", "Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs", "= {} for v, s in constraints.items(): new_vs = renaming.get(v,", "if case is None: self.follow_link(graph, link, {}) continue if s_exception", "value v = graph.getreturnvar() try: return self.binding(v) except KeyError: #", "issue calls to self.addpendingblock(). # The analysis of a block", "import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and", "from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import simplify,", "inputcells) # recursively proceed until no more pending block is", "block\"+at opid=\"\" if i is not None: opid = \"", "len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops =", "the # more general results invariant: e.g. if SomeImpossibleValue enters", "simplify, transform from rpython.annotator import model as annmodel, signature from", "XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function,", "block in self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block]", "def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = []", "simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None):", "the unannotated part #___ simplification (should be moved elsewhere?) _______", "s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg,", "annotating an additional # small helper creates. if self.added_blocks is", "renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs =", "if newblocks is None: newblocks = self.annotated # all of", "graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self)", "self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence): def", "in newblocks: for op in block.operations: if op.opname in ('simple_call',", "# annotations that are passed in, and don't annotate the", "The analysis of a block can be in three states:", "policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy()", "self.policy = policy if bookkeeper is None: bookkeeper = Bookkeeper(self)", "= {} # map {block: graph-containing-it} self.annotated = {} #", "tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is", "in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in", "self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if", "s_variable.knowntype else: return object else: raise TypeError(\"Variable or Constant instance", "graph-containing-it} self.annotated = {} # set of blocks already seen", "None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs =", "= self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for", "if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of:", "if new_ops is not None: block.operations[i:i+1] = new_ops if not", "not None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX", "if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const =", "self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph", "e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as", "self.break_at = None self.op = op self.opindex = opindex def", "can result in violations of the # more general results", "all graphs is annotated if self.added_blocks is not None: newgraphs", "exceptions that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if", "Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object):", "impossible values if s_out == s_ImpossibleValue: ignore_link = True s_out", "newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs)", "in constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs:", "= \" block\"+at opid=\"\" if i is not None: opid", "only follow the exceptional # branches. exits = [link for", "isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy =", "rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log = AnsiLogger(\"annrpython\")", "is dict, ( \"%r is not dict. please update %s.__getstate__\"", "self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished # make", "opid def flowin(self, graph, block): try: i = 0 while", "the new blocks that annotating an additional # small helper", "opindex def __repr__(self): if not self.break_at: break_at = \"?\" else:", "from rpython.annotator import model as annmodel, signature from rpython.annotator.model import", "self.notify[graph.returnblock] is a dictionary of call # points to this", "op.result op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference", "if s_variable: return s_variable.knowntype else: return object else: raise TypeError(\"Variable", "True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type", "block.at() if at: blk = \" block\"+at opid=\"\" if i", "annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks", "[] renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs):", "s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg)", "self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block] = False", "or Constant instance expected, \" \"got %r\" % (variable,)) def", "if s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out,", "inputs_s) #___ creating the annotations based on operations ______ def", "\"%r is not dict. please update %s.__getstate__\" % (key, self.__class__.__name__))", "validate(self): \"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def", "prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is None:", "# finished # make sure that the return variables of", "\"knowntypedata\", {}) else: knowntypedata = {} for link in exits:", "complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known", "self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph,", "the call operations in sync # with the flow object", "!= '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg))", "TypeError('Variable or Constant expected, got %r' % (arg,)) def binding(self,", "True blocked_blocks = [block for block, done in self.annotated.items() if", "{} for v, s in constraints.items(): new_vs = renaming.get(v, [])", "\"\"\"Recursively build annotations about the specific entry point.\"\"\" assert isinstance(function,", "{} self.complete() # invoke annotation simplifications for the new blocks", "graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence", "it. # About 'next': see test_annotate_iter_empty_container(). return else: # other", "transform from rpython.annotator import model as annmodel, signature from rpython.annotator.model", "set of graphs that have blocked blocks # --- end", "in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() #", "if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks:", "to always raise an exception. We then # swallow the", "else: newgraphs = self.translator.graphs #all of them got_blocked_blocks = False", "with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is", "is not dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key]", "block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________", "blocked blocks # --- end of debugging information --- self.frozen", "hack for debug tools only if not hasattr(e, '__annotator_block'): setattr(e,", "that annotating an additional # small helper creates. if self.added_blocks", "self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference", "raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is", "self.binding(v) except KeyError: # the function didn't reach any return", "type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value,", "callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None: if", "hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks'", "in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must", "in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated self.annotated[block]", "self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen", "i is not None: opid = \" op=%d\" % i", "complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def", "exits = [link for link in exits if link.exitcase ==", "graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if", "blocks until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if", "ignore_link = False inputs_s = [] renaming = defaultdict(list) for", "(key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level", "if block: at = block.at() if at: blk = \"", "is recorded for debugging --- self.blocked_graphs = {} # set", "if the merged cells changed, we must redo the analysis", "block, inputcells): # Merge the new 'cells' with each of", "avoiding propagated SomeImpossibleValues # to enter an op; the latter", "return statement so far. # (some functions actually never do,", "addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block,", "s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if", "inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register", "arg): \"Gives the SomeValue corresponding to the given Variable or", "whence callpositions[callback] = True # generalize the function's input arguments", "case = link.exitcase if case is None: self.follow_link(graph, link, {})", "AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in", "# must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph,", "function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy", "have bindings but we # still have to consider all", "-> SomeBool(const=False) ... # boom -- in the assert of", "of graphs not to annotate again self.blocked_blocks = {} #", "should try to progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex):", "i) raise else: # dead code removal: don't follow all", "of debugging information --- self.frozen = False if policy is", "pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface", "self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph, None)", "Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks", "+ opid def flowin(self, graph, block): try: i = 0", "annotations about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix", "assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block", "= self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values()", "# is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch", "True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells)", "zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code to", "is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self):", "which is immediately caught by # an exception handler. We", "ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link:", "least until we find we must generalize the # input", "\"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self,", "creating the annotations based on operations ______ def consider_op(self, op):", "if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable =", "None), None) -> SomeBool(const=False) ... # boom -- in the", "args of a block. assert len(block.inputargs) == len(inputcells) for a,", "is None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue:", "if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self)", "import simplify, transform from rpython.annotator import model as annmodel, signature", "AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper", "is fine to always raise an exception. We then #", "0 while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph,", "____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self,", "== False: # the input variables of the block have", "log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See", "block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset", "False: # the input variables of the block have bindings", "caught by # an exception handler. We then only follow", "flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy):", "return ret #___ convenience high-level interface __________________ def build_types(self, function,", "finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None):", "_____________________ def processblock(self, graph, block): # Important: this is not", "None: try: pos = self.bookkeeper.position_key except AttributeError: pos = '?'", "if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else:", "return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc", "except annmodel.AnnotatorError as e: # note that UnionError is a", "a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg,", "cells changed, we must redo the analysis if unions !=", "(some functions actually never do, they always raise exceptions) return", "{} # set of graphs that have blocked blocks #", "in self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks)", "(pos, msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph,", "block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True for", "( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells,", "[link for link in block.exits if link.exitcase is not None]", "self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave()", "newgraphs = self.translator.graphs #all of them got_blocked_blocks = False in", "new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self,", "cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while", "that's it. # About 'next': see test_annotate_iter_empty_container(). return else: #", "return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type of", "not None: if callable(whence): def callback(): whence(self, graph) else: callback", "AttributeError: self.break_at = None self.op = op self.opindex = opindex", "have blocked blocks # --- end of debugging information ---", "key not in attrs: assert type(value) is dict, ( \"%r", "import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import", "self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph =", "renaming = defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input)", "block.operations: if op.opname in ('simple_call', 'call_args'): yield op # some", "arg.annotation = s_value def warning(self, msg, pos=None): if pos is", "later by reflowing). Throw the BlockedInference up to # processblock().", "# is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) ->", "added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in ret.items(): if", "self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks", "list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def", "set of blocks already seen self.added_blocks = None # see", "'\\n'.join(source_lines(graph, block, None, long=True)) raise # if the merged cells", "get_exception(self, operation): \"\"\" Return the annotation for all exceptions that", "if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception,", "# some blocks are partially annotated if op.result.annotation is None:", "def mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells'", "self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False #", "the annotations based on operations ______ def consider_op(self, op): #", "def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes)", "# generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) #", "hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of", "# has side effects if translator is None: # interface", "= block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant():", "Safety-check the new # annotations that are passed in, and", "self.notify: # reflow from certain positions when this block is", "!= s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else:", "= graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem()", "initial bindings for the input args of a block. assert", "re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells):", "to annotate again self.blocked_blocks = {} # set of {blocked_block:", "them for block in newblocks: for op in block.operations: if", "s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results are valid\"\"\"", "the operations in the block. # * self.annotated[block] == graph-containing-block:", "BlockedInference(self, op, -1) # the operation cannot succeed assert isinstance(resultcell,", "def annotate_helper(self, function, args_s, policy=None): if policy is None: from", "None: self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break", "# to enter an op; the latter can result in", "try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except", "main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self,", "progress elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator = annotator", "passed in, and don't annotate the old # graph --", "self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got %r' %", "graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing", "self self.translator = translator self.pendingblocks = {} # map {block:", "for tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator", "already low-level operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg", "= variable.annotation if s_variable: return s_variable.knowntype else: return object else:", "case is None: self.follow_link(graph, link, {}) continue if s_exception ==", "self.annotated[block] == graph-containing-block: # analysis done (at least until we", "s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case)", "= {} # set of blocks already seen self.added_blocks =", "renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] =", "inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved =", "elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep", "graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy)", "e: # Add source code to the UnionError e.source =", "if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming =", "hopefully be solved # later by reflowing). Throw the BlockedInference", "t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul)", "if key not in attrs: assert type(value) is dict, (", "exits: case = link.exitcase if case is None: self.follow_link(graph, link,", "= link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and", "given input cells.\"\"\" if graph in self.fixed_graphs: # special case", "we # still have to consider all the operations in", "pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import", "s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if", "self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at", "in exits: case = link.exitcase if case is None: self.follow_link(graph,", "for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in", "is None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else:", "'added_blocks' is used by rpython.annlowlevel to # detect which are", "link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints)", "not to annotate again self.blocked_blocks = {} # set of", "if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks", "self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc =", "= [link for link in block.exits if link.exitcase is not", "policy = AnnotatorPolicy() # make input arguments and set their", "the function didn't reach any return statement so far. #", "= policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy =", "e.source = gather_error(self, graph, block, i) raise else: # dead", "assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and", "typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old", "try: self.flowin(graph, block) except BlockedInference as e: self.annotated[block] = False", "elsewhere.\"\"\" def __init__(self, annotator, op, opindex): self.annotator = annotator try:", "in several phases: calling # a graph that has already", "function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific", "block) raise # The dict 'added_blocks' is used by rpython.annlowlevel", "`operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is", "tests from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator =", "s_value): s_old = arg.annotation if s_old is not None: if", "None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX", "s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i =", "KeyError: # the function didn't reach any return statement so", "have ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}}", "= [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as", "self.annotated.get(block) if graph: graphs[graph] = True for graph in graphs:", "# reflow from certain positions when this block is done", "if callable(whence): def callback(): whence(self, graph) else: callback = whence", "import TranslationContext translator = TranslationContext() translator.annotator = self self.translator =", "dict, ( \"%r is not dict. please update %s.__getstate__\" %", "#print '* processblock', block, cells self.annotated[block] = graph if block", "_______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset,", "{} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for", "processblock() below self.links_followed = {} # set of links that", "resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation", "# self.flowin() can only issue calls to self.addpendingblock(). # The", "s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out", "= AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph,", "valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding to", "then # swallow the BlockedInference and that's it. # About", "generalize the function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get", "inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block]", "else: callback = whence callpositions[callback] = True # generalize the", "op; the latter can result in violations of the #", "known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch)", "# set of blocks already seen self.added_blocks = None #", "Constant instance expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self):", "v, s in constraints.items(): new_vs = renaming.get(v, []) for new_v", "def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___", "for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert", "which triggers a reflow whenever the # return block of", "pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos,", "block, i)): new_ops = op.transform(self) if new_ops is not None:", "set of graphs not to annotate again self.blocked_blocks = {}", "= {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {}", "graph = self.annotated.get(block) if graph: graphs[graph] = True for graph", "dead code removal: don't follow all exits if the exitswitch", "not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False", "ignore the unannotated part #___ simplification (should be moved elsewhere?)", "from rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self", "in attrs: assert type(value) is dict, ( \"%r is not", "renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating", "the new # annotations that are passed in, and don't", "# is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom --", "__init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects", "Important: this is not called recursively. # self.flowin() can only", "the assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg),", "has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is", "opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError:", "is None: break # ignore the unannotated part #___ simplification", "not None: newgraphs = [self.annotated[block] for block in self.added_blocks] newgraphs", "is a subclass e.source = gather_error(self, graph, block, i) raise", "isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation", "block can be in three states: # * block not", "# branches. exits = [link for link in block.exits if", "isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s", "try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op", "cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False #", "is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break", "which it is fine to always raise an exception. We", "# set of graphs that have blocked blocks # ---", "link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type,", "\"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface", "type(value) is dict, ( \"%r is not dict. please update", "\" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list", "newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs", "= difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr(", "\"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\" def __init__(self,", "# return block of this graph has been analysed. callpositions", "def processblock(self, graph, block): # Important: this is not called", "______ def consider_op(self, op): # let's be careful about avoiding", "Variable, Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator", "new_ops if not new_ops: continue new_ops[-1].result = op.result op =", "block.exits if link.exitcase is not None] elif e.op.opname in ('simple_call',", "# About 'next': see test_annotate_iter_empty_container(). return else: # other cases", "= (graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge", "block): assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block]", "will # always raise an exception which is immediately caught", "always raise an exception. We then # swallow the BlockedInference", "[]) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out,", "s_exitswitch.const] if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for", "for graph in newgraphs: v = graph.getreturnvar() if v.annotation is", "= \" op=%d\" % i return repr(graph) + blk +", "= (graph, e.opindex) except Exception as e: # hack for", "= True def reflowpendingblock(self, graph, block): assert not self.frozen assert", "(at least until we find we must generalize the #", "--- self.blocked_graphs = {} # set of graphs that have", "# ignore links that try to pass impossible values if", "s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items(): new_vs", "assert not self.frozen if block not in self.annotated: self.bindinputargs(graph, block,", "= self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True", "states: # * block not in self.annotated: # never seen", "enter an op; the latter can result in violations of", "try: self.added_blocks = {} self.complete() # invoke annotation simplifications for", "def annotation(self, arg): \"Gives the SomeValue corresponding to the given", "is not None: newgraphs = [self.annotated[block] for block in self.added_blocks]", "is the case where the last operation of the block", "rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments", "checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong", "exits = [link for link in block.exits if link.exitcase is", "not new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op)", "def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph, block)", "self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph)", "t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old =", "block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result = op.result", "in blocks _____________________ def processblock(self, graph, block): # Important: this", "in ('simple_call', 'call_args'): yield op # some blocks are partially", "annotate_helper(self, function, args_s, policy=None): if policy is None: from rpython.annotator.policy", "simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs =", "op, -1) resultcell = op.consider(self) if resultcell is None: resultcell", "= newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block,", "will hopefully be solved # later by reflowing). Throw the", "Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s =", "op in block.operations: if op.opname in ('simple_call', 'call_args'): yield op", "the situation is currently blocked, and that it should try", "else: raise TypeError('Variable or Constant expected, got %r' % (arg,))", "cells self.annotated[block] = graph if block in self.blocked_blocks: del self.blocked_blocks[block]", "if not new_ops: continue new_ops[-1].result = op.result op = new_ops[0]", "link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase,", "blk + opid def flowin(self, graph, block): try: i =", "{positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not to", "not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old))", "None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" %", "args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy =", "never seen the block. # * self.annotated[block] == False: #", "extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is", "newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def", "import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy if", "mergeinputargs(self, graph, block, inputcells): # Merge the new 'cells' with", "for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v,", "except Exception as e: # hack for debug tools only", "None) -> SomeBool(const=False) ... # boom -- in the assert", "part #___ simplification (should be moved elsewhere?) _______ def simplify(self,", "are the operations for # which it is fine to", "zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if", "s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value", "Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg,", "that the return variables of all graphs is annotated if", "about avoiding propagated SomeImpossibleValues # to enter an op; the", "= self.bookkeeper.position_key except AttributeError: pos = '?' if pos !=", "= graph assert block in self.annotated self.annotated[block] = False #", "not None: opid = \" op=%d\" % i return repr(graph)", "= self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True", "s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link", "= \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s", "# * block not in self.annotated: # never seen the", "is not None: block.operations[i:i+1] = new_ops if not new_ops: continue", "block, None, long=True)) raise # if the merged cells changed,", "attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy", "TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks = {}", "raise else: # dead code removal: don't follow all exits", "self.annotated = {} # set of blocks already seen self.added_blocks", "v = graph.getreturnvar() try: return self.binding(v) except KeyError: # the", "# a graph that has already been rtyped. Safety-check the", "operations in sync # with the flow object space. These", "done in self.annotated.items() if done is False] assert len(blocked_blocks) ==", "callback is a position else: callback() def follow_link(self, graph, link,", "# set of links that have ever been followed self.notify", "annotate again self.blocked_blocks = {} # set of {blocked_block: (graph,", "SomeValue corresponding to the given Variable or Constant.\" s_arg =", "self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value v", "#___ simplification (should be moved elsewhere?) _______ def simplify(self, block_subset=None,", "flowing annotations in blocks _____________________ def processblock(self, graph, block): #", "None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception", "pos=None): if pos is None: try: pos = self.bookkeeper.position_key except", "def __repr__(self): if not self.break_at: break_at = \"?\" else: break_at", "the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no", "def complete(self): \"\"\"Process pending blocks until none is left.\"\"\" while", "inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph", "them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph", "== graph-containing-block: # analysis done (at least until we find", "subclass e.source = gather_error(self, graph, block, i) raise else: #", "bindings but we # still have to consider all the", "saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks =", "if whence is not None: if callable(whence): def callback(): whence(self,", "Return the annotation for all exceptions that `operation` may raise.", "s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif", "= [self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks", "-- it's already low-level operations! for a, s_newarg in zip(block.inputargs,", "constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in", "input variables). #print '* processblock', block, cells self.annotated[block] = graph", "expected, got %r' % (arg,)) def binding(self, arg): \"Gives the", "= self.annotation(arg) if s_arg is None: raise KeyError return s_arg", "recorded for debugging --- self.blocked_graphs = {} # set of", "if op.opname in ('simple_call', 'call_args'): yield op # some blocks", "and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming", "rpython.translator.translator import TranslationContext translator = TranslationContext() translator.annotator = self self.translator", "{} # set of {blocked_block: (graph, index)} # --- the", "or Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant):", "have to consider all the operations in the block. #", "None # see processblock() below self.links_followed = {} # set", "number of args # register the entry point self.addpendinggraph(flowgraph, inputcells)", "input arguments and set their type args_s = [self.typeannotation(t) for", "if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the", "= self.annotated # all of them for block in newblocks:", "input # variables. oldcells = [self.binding(a) for a in block.inputargs]", "op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self)", "processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError", "when this block is done for callback in self.notify[block]: if", "of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {})", "self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def", "renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert", "for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False", "key, value in ret.items(): if key not in attrs: assert", "TypeError(\"Variable or Constant instance expected, \" \"got %r\" % (variable,))", "debugging --- self.blocked_graphs = {} # set of graphs that", "variables. oldcells = [self.binding(a) for a in block.inputargs] try: unions", "s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc !=", "consider all the operations in the block. # * self.annotated[block]", "raise # if the merged cells changed, we must redo", "knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {}", "# the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result,", "do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key):", "= {} # set of {blocked_block: (graph, index)} # ---", "= [block for block, done in self.annotated.items() if done is", "= arg.annotation if s_old is not None: if not s_value.contains(s_old):", "About 'next': see test_annotate_iter_empty_container(). return else: # other cases are", "for all exceptions that `operation` may raise. \"\"\" can_only_throw =", "currently blocked, and that it should try to progress elsewhere.\"\"\"", "self.reflowfromposition(callback) # callback is a position else: callback() def follow_link(self,", "= [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert", "if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in", "oldcells = [self.binding(a) for a in block.inputargs] try: unions =", "assert of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue):", "this block is done for callback in self.notify[block]: if isinstance(callback,", "prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s)", "len(inputcells) == nbarg # wrong number of args # register", "for block, done in self.annotated.items() if done is False] assert", "has already been rtyped. Safety-check the new # annotations that", "defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from", "annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that UnionError", "block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending", "arguments and set their type args_s = [self.typeannotation(t) for t", "is None: raise KeyError return s_arg def typeannotation(self, t): return", "of {blocked_block: (graph, index)} # --- the following information is", "= ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if", "args_s = [self.typeannotation(t) for t in input_arg_types] # XXX hack", "graphs that have blocked blocks # --- end of debugging", "not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value, s_old))", "in, and don't annotate the old # graph -- it's", "newblocks is None: newblocks = self.annotated # all of them", "annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell", "links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for", "def bindinputargs(self, graph, block, inputcells): # Create the initial bindings", "by rpython.annlowlevel to # detect which are the new blocks", "s_exitswitch.is_constant(): exits = [link for link in exits if link.exitcase", "self.__class__.__name__)) ret[key] = {} return ret #___ convenience high-level interface", "hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e:", "self.annotated self.annotated[block] = False # must re-flow self.blocked_blocks[block] = (graph,", "self.added_blocks = {} self.complete() # invoke annotation simplifications for the", "= policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper", "extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else: graphs", "= self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s)", "= getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for", "instance expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return", "input cells.\"\"\" if graph in self.fixed_graphs: # special case for", "graph.getreturnvar() try: return self.binding(v) except KeyError: # the function didn't", "far. # (some functions actually never do, they always raise", "rpython.translator import simplify, transform from rpython.annotator import model as annmodel,", "raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index", "reflow whenever the # return block of this graph has", "s_out = pair(s_out, s_constraint).improve() # ignore links that try to", "input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s", "are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding", "detect which are the new blocks that annotating an additional", "# Add source code to the UnionError e.source = '\\n'.join(source_lines(graph,", "if block_subset is None: graphs = self.translator.graphs else: graphs =", "(types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s =", "unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming):", "except KeyError: # the function didn't reach any return statement", "inference engine that the situation is currently blocked, and that", "exception which is immediately caught by # an exception handler.", "typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const", "BlockedInference(Exception): \"\"\"This exception signals the type inference engine that the", "self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks is", "policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul)", "s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph,", "that are passed in, and don't annotate the old #", "... # boom -- in the assert of setbinding() for", "policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in ret.items():", "BlockedInference up to # processblock(). e.opindex = i raise except", "(graph, index)} # --- the following information is recorded for", "'?' if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/ %s\"", "self.fixed_graphs: # special case for annotating/rtyping in several phases: calling", "self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy", "in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell =", "annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy)", "desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function, args_s,", "an additional # small helper creates. if self.added_blocks is not", "unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of =", "from certain positions when this block is done for callback", "calls to self.addpendingblock(). # The analysis of a block can", "are partially annotated if op.result.annotation is None: break # ignore", "on operations ______ def consider_op(self, op): # let's be careful", "True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is", "can only issue calls to self.addpendingblock(). # The analysis of", "False in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph]", "self.translator.graphs else: graphs = {} for block in block_subset: graph", "called recursively. # self.flowin() can only issue calls to self.addpendingblock().", "flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) ==", "getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level", "three states: # * block not in self.annotated: # never", "in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___", "variable.annotation if s_variable: return s_variable.knowntype else: return object else: raise", "translator = TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks", "in block.exits if link.exitcase is not None] elif e.op.opname in", "newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out =", "block, cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block]", "for debugging --- self.blocked_graphs = {} # set of graphs", "if s_exitswitch.is_constant(): exits = [link for link in exits if", "block_subset is None: graphs = self.translator.graphs else: graphs = {}", "with the given input cells.\"\"\" if graph in self.fixed_graphs: #", "effects if translator is None: # interface for tests from", "inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an entry point", "= s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self,", "based on operations ______ def consider_op(self, op): # let's be", "isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata", "policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy", "is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks)", "but we # still have to consider all the operations", "def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert", "from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make input", "return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key", "other cases are problematic (but will hopefully be solved #", "got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks =", "self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] = (graph,", "complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved = self.policy,", "if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value,", "is not None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain", "break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc", "from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy =", "follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value", "break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at", "v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the", "in the assert of setbinding() for arg in op.args: if", "= annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at =", "= self.get_exception(op) for link in exits: case = link.exitcase if", "pos is None: try: pos = self.bookkeeper.position_key except AttributeError: pos", "= True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based", "a position else: callback() def follow_link(self, graph, link, constraints): assert", "# always raise an exception which is immediately caught by", "for the input args of a block. assert len(block.inputargs) ==", "that try to pass impossible values if s_out == s_ImpossibleValue:", "args_s, policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy", "self.translator.graphs #all of them got_blocked_blocks = False in self.annotated.values() if", "new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] =", "in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out =", "of them for block in newblocks: for op in block.operations:", "reach any return statement so far. # (some functions actually", "#___ flowing annotations in blocks _____________________ def processblock(self, graph, block):", "zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out)", "'call_args', 'next'): # XXX warning, keep the name of the", "debugging information --- self.frozen = False if policy is None:", "variable): \"\"\"Return the known type of a control flow graph", "== len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell)", "= {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set", "in self.notify: # reflow from certain positions when this block", "block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in", "(graph, e.opindex) except Exception as e: # hack for debug", "import model as annmodel, signature from rpython.annotator.model import ( typeof,", "False if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy", "source code to the UnionError e.source = '\\n'.join(source_lines(graph, block, None,", "= bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed", "not dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] =", "(types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if", "type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out", "{} return ret #___ convenience high-level interface __________________ def build_types(self,", "self.policy = prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy", "i = position_key blk = \"\" if block: at =", "input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific entry", "return else: # other cases are problematic (but will hopefully", "\"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() #", "self.policy = AnnotatorPolicy() else: self.policy = policy if bookkeeper is", "= annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell", "changed, we must redo the analysis if unions != oldcells:", "the block. # * self.annotated[block] == False: # the input", "of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for", "any return statement so far. # (some functions actually never", "= self.policy self.policy = policy self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally:", "block will # always raise an exception which is immediately", "e.opindex) except Exception as e: # hack for debug tools", "always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block,", "pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def", "attrs: assert type(value) is dict, ( \"%r is not dict.", "# all of them for block in newblocks: for op", "of the block's existing input # variables. oldcells = [self.binding(a)", "= None self.op = op self.opindex = opindex def __repr__(self):", "difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation,", "inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return", "register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until", "None: newblocks = self.annotated # all of them for block", "an entry point into block with the given input cells.\"\"\"", "new blocks that annotating an additional # small helper creates.", "s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming", "BlockedInference(self, op, -1) resultcell = op.consider(self) if resultcell is None:", "done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self,", "removal: don't follow all exits if the exitswitch # is", "= op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif", "rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from", "warning, keep the name of the call operations in sync", "as e: if e.op is block.raising_op: # this is the", "branches. exits = [link for link in block.exits if link.exitcase", "(format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from", "for v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type:", "= op.result op = new_ops[0] self.consider_op(op) i += 1 except", "assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit()", "or Constant.\" s_arg = self.annotation(arg) if s_arg is None: raise", "ever been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs", "#___ creating the annotations based on operations ______ def consider_op(self,", "for RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None,", "callback(): whence(self, graph) else: callback = whence callpositions[callback] = True", "bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def", "graph, block, cells): \"\"\"Register an entry point into block with", "assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const =", "#___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells):", "'next': see test_annotate_iter_empty_container(). return else: # other cases are problematic", "annotator, op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key", "given Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation elif", "engine that the situation is currently blocked, and that it", "Constant, checkgraph from rpython.translator import simplify, transform from rpython.annotator import", "assert type(value) is dict, ( \"%r is not dict. please", "graph in newgraphs: v = graph.getreturnvar() if v.annotation is None:", "in self.fixed_graphs: # special case for annotating/rtyping in several phases:", "not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict", "s_value def warning(self, msg, pos=None): if pos is None: try:", "self.annotation(arg) if s_arg is None: raise KeyError return s_arg def", "= whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) #", "= constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that", "if self.added_blocks is not None: newgraphs = [self.annotated[block] for block", "for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block", "self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True", "if block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link", "defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable,", "# invoke annotation simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally:", "is a position else: callback() def follow_link(self, graph, link, constraints):", "in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if", "information is recorded for debugging --- self.blocked_graphs = {} #", "block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of", "= \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split()", "is None: graphs = self.translator.graphs else: graphs = {} for", "# map {block: graph-containing-it} self.annotated = {} # set of", "source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph from rpython.translator import", "ret #___ convenience high-level interface __________________ def build_types(self, function, input_arg_types,", "for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] =", "'* processblock', block, cells self.annotated[block] = graph if block in", "# more general results invariant: e.g. if SomeImpossibleValue enters is_", "import Variable, Constant, checkgraph from rpython.translator import simplify, transform from", "assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if", "boom -- in the assert of setbinding() for arg in", "= typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant():", "i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block, i)):", "= False # must flowin. self.blocked_blocks[block] = (graph, None) def", "= link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert", "succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) #", "contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert", "reflowing). Throw the BlockedInference up to # processblock(). e.opindex =", "= self.notify.setdefault(graph.returnblock, {}) if whence is not None: if callable(whence):", "op.result.annotation is None: break # ignore the unannotated part #___", "None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results", "e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool", "+= 1 except BlockedInference as e: if e.op is block.raising_op:", "policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator", "self.blocked_graphs = {} # set of graphs that have blocked", "graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase,", "True def reflowpendingblock(self, graph, block): assert not self.frozen assert graph", "except annmodel.UnionError as e: # Add source code to the", "typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if", "graphs = self.translator.graphs else: graphs = {} for block in", "constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links that try", "object space. These are the operations for # which it", "make input arguments and set their type args_s = [self.typeannotation(t)", "self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None) try: return", "the case where the last operation of the block will", "didn't reach any return statement so far. # (some functions", "# note that UnionError is a subclass e.source = gather_error(self,", "import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error,", "s_out def whereami(self, position_key): graph, block, i = position_key blk", "break # finished # make sure that the return variables", "complete(self): \"\"\"Process pending blocks until none is left.\"\"\" while True:", "# failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception", "defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out,", "= graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self):", "annotations that are passed in, and don't annotate the old", "calling # a graph that has already been rtyped. Safety-check", "more general results invariant: e.g. if SomeImpossibleValue enters is_ #", "that UnionError is a subclass e.source = gather_error(self, graph, block,", "Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for", "%s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return ret #___", "{}) continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case))", "= i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e:", "# with the flow object space. These are the operations", "self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False)", "graph, tag) # self.notify[graph.returnblock] is a dictionary of call #", "e: if e.op is block.raising_op: # this is the case", "# analysis done (at least until we find we must", "if i is not None: opid = \" op=%d\" %", "new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool()", "s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link,", "--- self.frozen = False if policy is None: from rpython.annotator.policy", "notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key,", "recursively. # self.flowin() can only issue calls to self.addpendingblock(). #", "operation): \"\"\" Return the annotation for all exceptions that `operation`", "#___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock,", "graph.startblock, inputcells) # get the (current) return value v =", "ret = self.__dict__.copy() for key, value in ret.items(): if key", "arg, s_value): s_old = arg.annotation if s_old is not None:", "new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1] =", "\" op=%d\" % i return repr(graph) + blk + opid", "graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert", "interface for tests from rpython.translator.translator import TranslationContext translator = TranslationContext()", "# the input variables of the block have bindings but", "AnnotatorPolicy policy = AnnotatorPolicy() # make input arguments and set", "= knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify:", "renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target,", "be in three states: # * block not in self.annotated:", "else: self.policy = policy if bookkeeper is None: bookkeeper =", "in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value])", "entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more", "self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph assert", "their type args_s = [self.typeannotation(t) for t in input_arg_types] #", "# XXX warning, keep the name of the call operations", "annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection,", "= saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg =", "be careful about avoiding propagated SomeImpossibleValues # to enter an", "bind resultcell to op.result def get_exception(self, operation): \"\"\" Return the", "s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) #", "'__annotator_block', block) raise # The dict 'added_blocks' is used by", "# wrong number of args # register the entry point", "in zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) ==", "def consider_op(self, op): # let's be careful about avoiding propagated", "self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block, graph", "v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve()", "len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of args", "= parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a", "# see processblock() below self.links_followed = {} # set of", "as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance,", "op self.opindex = opindex def __repr__(self): if not self.break_at: break_at", "then only follow the exceptional # branches. exits = [link", "renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if", "whence(self, graph) else: callback = whence callpositions[callback] = True #", "raise an exception. We then # swallow the BlockedInference and", "links that try to pass impossible values if s_out ==", "description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry", "parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph,", "already been rtyped. Safety-check the new # annotations that are", "interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if", "SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph,", "self.blocked_blocks = {} # set of {blocked_block: (graph, index)} #", "else: callback() def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase,", "all exceptions that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self)", "in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell", "finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True):", "in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference as", "link.target, inputs_s) #___ creating the annotations based on operations ______", "long=True)) raise # if the merged cells changed, we must", "new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool) newcell", "self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete()", "try: return self.binding(v) except KeyError: # the function didn't reach", "we must generalize the # input variables). #print '* processblock',", "if e.op is block.raising_op: # this is the case where", "of setbinding() for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise", "\"\"\"This exception signals the type inference engine that the situation", "blocks that annotating an additional # small helper creates. if", "try to pass impossible values if s_out == s_ImpossibleValue: ignore_link", "isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list)", "s_old = arg.annotation if s_old is not None: if not", "still have to consider all the operations in the block.", "[annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e:", "assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const", "position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if newblocks", "in self.annotated.values() if got_blocked_blocks: for graph in self.blocked_graphs.values(): self.blocked_graphs[graph] =", "is not None: if callable(whence): def callback(): whence(self, graph) else:", "in block.operations: if op.opname in ('simple_call', 'call_args'): yield op #", "(graph, None) def bindinputargs(self, graph, block, inputcells): # Create the", "from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines)", "this func which triggers a reflow whenever the # return", "v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type,", "blk = \"\" if block: at = block.at() if at:", "else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at,", "link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase,", "in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source code", "the block. # * self.annotated[block] == graph-containing-block: # analysis done", "\"\"\" Return the annotation for all exceptions that `operation` may", "that has already been rtyped. Safety-check the new # annotations", "--- end of debugging information --- self.frozen = False if", "type inference engine that the situation is currently blocked, and", "zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False # must flowin.", "log.WARNING(\"%s does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" %", "flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an entry", "a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________", "violations of the # more general results invariant: e.g. if", "translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if", "bindinputargs(self, graph, block, inputcells): # Create the initial bindings for", "( self.translator.config.translation.check_str_without_nul) flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point:", "from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error", "s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell =", "inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the", "policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy", "annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the", "can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else:", "to pass impossible values if s_out == s_ImpossibleValue: ignore_link =", "# swallow the BlockedInference and that's it. # About 'next':", "def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper", "got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks: for graph in", "if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out,", "it is fine to always raise an exception. We then", "in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in constraints.items():", "constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s in", "self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v", "graph, block): try: i = 0 while i < len(block.operations):", "if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise # The", "convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False):", "constraints) if block in self.notify: # reflow from certain positions", "[block for block, done in self.annotated.items() if done is False]", "import types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger", "s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] =", "a control flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable,", "repr(graph) + blk + opid def flowin(self, graph, block): try:", "block in newblocks: for op in block.operations: if op.opname in", "in self.annotated: # never seen the block. # * self.annotated[block]", "for link in block.exits if link.exitcase is not None] elif", "pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret =", "inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function)", "if resultcell is None: resultcell = s_ImpossibleValue elif resultcell ==", "= block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if", "finished # make sure that the return variables of all", "= policy try: self.added_blocks = {} self.complete() # invoke annotation", "op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops if", "if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception", "\"Gives the SomeValue corresponding to the given Variable or Constant.\"", "last operation of the block will # always raise an", "self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph,", "block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] =", "#raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v =", "of args # register the entry point self.addpendinggraph(flowgraph, inputcells) #", "at: blk = \" block\"+at opid=\"\" if i is not", "v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const", "index)} # --- the following information is recorded for debugging", "must redo the analysis if unions != oldcells: self.bindinputargs(graph, block,", "self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function,", "= AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description", "not self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at) return", "self.flowin() can only issue calls to self.addpendingblock(). # The analysis", "i = 0 while i < len(block.operations): op = block.operations[i]", "return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable", "link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable):", "for block in newblocks: for op in block.operations: if op.opname", "the SomeValue corresponding to the given Variable or Constant.\" s_arg", "not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self): while self.pendingblocks: block,", "self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue corresponding to the", "break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op)", "build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells)", "at = block.at() if at: blk = \" block\"+at opid=\"\"", "callpositions[callback] = True # generalize the function's input arguments self.addpendingblock(graph,", "exception handler. We then only follow the exceptional # branches.", "if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else:", "False inputs_s = [] renaming = defaultdict(list) for v_out, v_input", "is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False)", "(current) return value v = graph.getreturnvar() try: return self.binding(v) except", "function didn't reach any return statement so far. # (some", "input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return", "assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells):", "= format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in", "def flowin(self, graph, block): try: i = 0 while i", "self.fixed_graphs = {} # set of graphs not to annotate", "AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells", "unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError", "def setbinding(self, arg, s_value): s_old = arg.annotation if s_old is", "block.raising_op s_exception = self.get_exception(op) for link in exits: case =", "to the given Variable or Constant.\" if isinstance(arg, Variable): return", "v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException))", "wrong number of args # register the entry point self.addpendinggraph(flowgraph,", "# register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively proceed", "for # which it is fine to always raise an", "is used by rpython.annlowlevel to # detect which are the", "# boom -- in the assert of setbinding() for arg", "except BlockedInference as e: self.annotated[block] = False # failed, hopefully", "s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\",", "v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value", "complete_now=complete_now) def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy", "an exception which is immediately caught by # an exception", "graph def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph,", "isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const", "get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy", "self.annotated[block] == False: # the input variables of the block", "policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy):", "defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out", "return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells):", "= [] renaming = defaultdict(list) for v_out, v_input in zip(link.args,", "of blocks already seen self.added_blocks = None # see processblock()", "self.added_blocks self.policy = policy try: self.added_blocks = {} self.complete() #", "{} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of", "self.bookkeeper.position_key except AttributeError: pos = '?' if pos != '?':", "a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2", "a block. assert len(block.inputargs) == len(inputcells) for a, cell in", "msg)) #___ interface for annotator.bookkeeper _______ def recursivecall(self, graph, whence,", "in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) flowgraph,", "perform_normalizations(self) #___ flowing annotations in blocks _____________________ def processblock(self, graph,", "input variables of the block have bindings but we #", "# --- end of debugging information --- self.frozen = False", "is not None: opid = \" op=%d\" % i return", "must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block,", "if link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args',", "s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out =", "= self.policy, self.added_blocks self.policy = policy try: self.added_blocks = {}", "self.added_blocks is not None: newgraphs = [self.annotated[block] for block in", "is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation", "exits if the exitswitch # is known exits = block.exits", "elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant", "careful about avoiding propagated SomeImpossibleValues # to enter an op;", "let's be careful about avoiding propagated SomeImpossibleValues # to enter", "typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out, v_input", "log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def", "{} # set of links that have ever been followed", "if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value)", "yield op # some blocks are partially annotated if op.result.annotation", "# make sure that the return variables of all graphs", "self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} #", "build annotations about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType),", "Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected, got", "setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is used", "from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log =", "that have ever been followed self.notify = {} # {block:", "this is not called recursively. # self.flowin() can only issue", "\"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of", "if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag =", "don't follow all exits if the exitswitch # is known", "s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception =", "translator.annotator = self self.translator = translator self.pendingblocks = {} #", "warning(self, msg, pos=None): if pos is None: try: pos =", "else: assert not self.frozen if block not in self.annotated: self.bindinputargs(graph,", "annotations in blocks _____________________ def processblock(self, graph, block): # Important:", "keep the name of the call operations in sync #", "blocks already seen self.added_blocks = None # see processblock() below", "processblock', block, cells self.annotated[block] = graph if block in self.blocked_blocks:", "newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata", "__getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen", "self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type =", "annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy()", "annmodel.TLS.check_str_without_nul = ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy)", "None: break # ignore the unannotated part #___ simplification (should", "s_arg is None: raise KeyError return s_arg def typeannotation(self, t):", "graph -- it's already low-level operations! for a, s_newarg in", "1 except BlockedInference as e: if e.op is block.raising_op: #", "for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link,", "self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph,", "raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if", "= self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out", "e.op is block.raising_op: # this is the case where the", "annotated if op.result.annotation is None: break # ignore the unannotated", "= False if policy is None: from rpython.annotator.policy import AnnotatorPolicy", "dictionary of call # points to this func which triggers", "is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable):", "graph, block, i) raise else: # dead code removal: don't", "{} # set of graphs not to annotate again self.blocked_blocks", "annotated if self.added_blocks is not None: newgraphs = [self.annotated[block] for", "debug tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block)", "none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks:", "isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result def", "new_ops: continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i", "# --- the following information is recorded for debugging ---", "(but will hopefully be solved # later by reflowing). Throw", "the following information is recorded for debugging --- self.blocked_graphs =", "= annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op", "= op self.opindex = opindex def __repr__(self): if not self.break_at:", "AnnotatorPolicy() # make input arguments and set their type args_s", "break # ignore the unannotated part #___ simplification (should be", "is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom -- in", "def complete_pending_blocks(self): while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block)", "These are the operations for # which it is fine", "graph in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for", "-1) resultcell = op.consider(self) if resultcell is None: resultcell =", "self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until none", "# variables. oldcells = [self.binding(a) for a in block.inputargs] try:", "merged cells changed, we must redo the analysis if unions", "self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block, done", "BlockedInference as e: self.annotated[block] = False # failed, hopefully temporarily", "return graph def complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy", "of links that have ever been followed self.notify = {}", "SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import", "i raise except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: #", "self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on operations", "self.blocked_blocks[block] = (graph, None) def bindinputargs(self, graph, block, inputcells): #", "'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable", "TranslationContext translator = TranslationContext() translator.annotator = self self.translator = translator", "None: graphs = self.translator.graphs else: graphs = {} for block", "= AnnotatorPolicy() # make input arguments and set their type", "in exits if link.exitcase == s_exitswitch.const] if block.canraise: op =", "# must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph,", "issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = [] renaming =", "from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack", "= ( self.translator.config.translation.check_str_without_nul) graph, inputcells = self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph,", "value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value] = {} for v, s", "the given input cells.\"\"\" if graph in self.fixed_graphs: # special", "only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise #", "None] elif e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning,", "rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant,", "= typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out = newcell", "We then # swallow the BlockedInference and that's it. #", "v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in", "of ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self,", "swallow the BlockedInference and that's it. # About 'next': see", "s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'):", "# other cases are problematic (but will hopefully be solved", "must generalize the # input variables). #print '* processblock', block,", "if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except", "s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType,", "def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about", "handler. We then only follow the exceptional # branches. exits", "return block of this graph has been analysed. callpositions =", "# Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None:", "call # points to this func which triggers a reflow", "('simple_call', 'call_args', 'next'): # XXX warning, keep the name of", "v_last_exc_type = link.last_exception v_last_exc_value = link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type))", "(should be moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): #", "whereami(self, position_key): graph, block, i = position_key blk = \"\"", "s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s does not", "= {} # set of graphs not to annotate again", "= s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant():", "block with the given input cells.\"\"\" if graph in self.fixed_graphs:", "\"\"\"Return the known type of a control flow graph variable,", "update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {} return ret", "annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op = op self.opindex", "op, opindex): self.annotator = annotator try: self.break_at = annotator.bookkeeper.position_key except", "len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for", "isinstance(v_last_exc_type, Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const", "phases: calling # a graph that has already been rtyped.", "= 0 while i < len(block.operations): op = block.operations[i] with", "left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break #", "# self.notify[graph.returnblock] is a dictionary of call # points to", "SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... # boom", "is immediately caught by # an exception handler. We then", "graph, block): assert not self.frozen assert graph not in self.fixed_graphs", "annmodel.AnnotatorError as e: # note that UnionError is a subclass", "args # register the entry point self.addpendinggraph(flowgraph, inputcells) # recursively", "None) def mergeinputargs(self, graph, block, inputcells): # Merge the new", "for annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence,", "% i return repr(graph) + blk + opid def flowin(self,", "the BlockedInference up to # processblock(). e.opindex = i raise", "(variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return self.bookkeeper.classdefs", "self.setbinding(op.result, resultcell) # bind resultcell to op.result def get_exception(self, operation):", "specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy", "%s\" % (pos, msg)) #___ interface for annotator.bookkeeper _______ def", "= graph if block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph,", "% (key, self.__class__.__name__)) ret[key] = {} return ret #___ convenience", "self.annotated.items() if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text", "parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of", "import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model", "s_variable: return s_variable.knowntype else: return object else: raise TypeError(\"Variable or", "simplify(self, block_subset=None, extra_passes=None): # Generic simplifications transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if", "#___ convenience high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True,", "self.added_blocks if newblocks is None: newblocks = self.annotated # all", "zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if", "of graphs that have blocked blocks # --- end of", "pos = '?' if pos != '?': pos = self.whereami(pos)", "+ blk + opid def flowin(self, graph, block): try: i", "the # return block of this graph has been analysed.", "self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations in", "def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph,", "some blocks are partially annotated if op.result.annotation is None: break", "operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result,", "link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out", "blocks _____________________ def processblock(self, graph, block): # Important: this is", "v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args:", "checkgraph from rpython.translator import simplify, transform from rpython.annotator import model", "analysis of a block can be in three states: #", "s_value.contains(s_old): log.WARNING(\"%s does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\"", "block. assert len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs,", "new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i += 1", "newblocks = self.added_blocks if newblocks is None: newblocks = self.annotated", "self.links_followed = {} # set of links that have ever", "position_key blk = \"\" if block: at = block.at() if", "processblock(self, graph, block): # Important: this is not called recursively.", "s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else:", "certain positions when this block is done for callback in", "generalize the # input variables). #print '* processblock', block, cells", "False # failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except", "the exceptional # branches. exits = [link for link in", "if self.added_blocks is not None: self.added_blocks[block] = True def reflowpendingblock(self,", "[self.annotated[block] for block in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks =", "the UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise #", "analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not None:", "got %r' % (arg,)) def binding(self, arg): \"Gives the SomeValue", "no more pending block is left if complete_now: self.complete() return", "self.added_blocks = None # see processblock() below self.links_followed = {}", "exception signals the type inference engine that the situation is", "= self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return", "= True # generalize the function's input arguments self.addpendingblock(graph, graph.startblock,", "op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue elif resultcell", "reflow from certain positions when this block is done for", "in ('simple_call', 'call_args', 'next'): # XXX warning, keep the name", "s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata", "\"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception))", "BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value)", "__future__ import absolute_import import types from collections import defaultdict from", "self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block, inputcells): #", "True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished #", "point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy", "s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {}", "else: raise TypeError(\"Variable or Constant instance expected, \" \"got %r\"", "Constant expected, got %r' % (arg,)) def binding(self, arg): \"Gives", "interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def", "don't annotate the old # graph -- it's already low-level", "follow the exceptional # branches. exits = [link for link", "Constant.\" if isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return", "self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = [] renaming = defaultdict(list) for v_out,", "type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s = []", "assert not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] =", "= (graph, None) def bindinputargs(self, graph, block, inputcells): # Create", "link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception", "values if s_out == s_ImpossibleValue: ignore_link = True s_out =", "raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None: return", "complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the specific entry point.\"\"\"", "op.opname in ('simple_call', 'call_args'): yield op # some blocks are", "= op.transform(self) if new_ops is not None: block.operations[i:i+1] = new_ops", "it's already low-level operations! for a, s_newarg in zip(block.inputargs, cells):", "= self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op) __str__", "as e: # Add source code to the UnionError e.source", "= renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v] = s", "for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul = (", "= self.annotated.get(block) if graph: graphs[graph] = True for graph in", "block, done in self.annotated.items() if done is False] assert len(blocked_blocks)", "arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1)", "= intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc)", "Constant): s_out.const = v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out)", "annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to", "= new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e:", "XXX warning, keep the name of the call operations in", "if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy =", "in sync # with the flow object space. These are", "parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary", "# {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs", "return variables of all graphs is annotated if self.added_blocks is", "[self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for", "the SomeValue corresponding to the given Variable or Constant.\" if", "False arg.annotation = s_value def warning(self, msg, pos=None): if pos", "AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import (format_blocked_annotation_error, gather_error,", "complete_helpers(self, policy): saved = self.policy, self.added_blocks self.policy = policy try:", "is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() #", "problematic (but will hopefully be solved # later by reflowing).", "a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block] = False", "('simple_call', 'call_args'): yield op # some blocks are partially annotated", "the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable)", "s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if", "self.get_call_parameters(function, args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def", "the old # graph -- it's already low-level operations! for", "SomeValue corresponding to the given Variable or Constant.\" if isinstance(arg,", "to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif isinstance(variable, Variable):", "is currently blocked, and that it should try to progress", "until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not", "annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata)", "opid=\"\" if i is not None: opid = \" op=%d\"", "not self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells)", "e: # hack for debug tools only if not hasattr(e,", "from __future__ import absolute_import import types from collections import defaultdict", "else: return object else: raise TypeError(\"Variable or Constant instance expected,", "whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock]", "import perform_normalizations log = AnsiLogger(\"annrpython\") class RPythonAnnotator(object): \"\"\"Block annotator for", "difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls import perform_normalizations log", "an op; the latter can result in violations of the", "for v_out in link.args: s_out = self.annotation(v_out) if v_out in", "= Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs = \"\"\"translator", "left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return", "{}) if whence is not None: if callable(whence): def callback():", "annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const = s_out.const s_out", "cannot succeed assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell)", "self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process", "None: if callable(whence): def callback(): whence(self, graph) else: callback =", "def callback(): whence(self, graph) else: callback = whence callpositions[callback] =", "blocked_blocks = [block for block, done in self.annotated.items() if done", "block not in self.annotated: # never seen the block. #", "annotations based on operations ______ def consider_op(self, op): # let's", "(arg,)) def binding(self, arg): \"Gives the SomeValue corresponding to the", "renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant():", "of call # points to this func which triggers a", "assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if", "of the block have bindings but we # still have", "= True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value):", "typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from", "if translator is None: # interface for tests from rpython.translator.translator", "inputcells, complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg", "and that it should try to progress elsewhere.\"\"\" def __init__(self,", "# small helper creates. if self.added_blocks is not None: self.added_blocks[block]", "= {} for block in block_subset: graph = self.annotated.get(block) if", "see test_annotate_iter_empty_container(). return else: # other cases are problematic (but", "hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items():", "general results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue,", "pos = self.bookkeeper.position_key except AttributeError: pos = '?' if pos", "if the exitswitch # is known exits = block.exits if", "format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs:", "Add source code to the UnionError e.source = '\\n'.join(source_lines(graph, block,", "== s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out)", "= {} # set of links that have ever been", "the block's existing input # variables. oldcells = [self.binding(a) for", "def get_exception(self, operation): \"\"\" Return the annotation for all exceptions", "# (some functions actually never do, they always raise exceptions)", "nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number", "# * self.annotated[block] == graph-containing-block: # analysis done (at least", "isinstance(arg, Variable): return arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else:", "[self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul =", "self.follow_raise_link(graph, link, s_matching_exc) s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch,", "newblocks: for op in block.operations: if op.opname in ('simple_call', 'call_args'):", "if s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s does", "the merged cells changed, we must redo the analysis if", "annotation for all exceptions that `operation` may raise. \"\"\" can_only_throw", "RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None):", "signature from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference)", "a subclass e.source = gather_error(self, graph, block, i) raise else:", "return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value): s_old = arg.annotation", "self.addpendingblock(). # The analysis of a block can be in", "may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw is None:", "def get_call_parameters(self, function, args_s, policy): desc = self.bookkeeper.getdesc(function) prevpolicy =", "return s_out def whereami(self, position_key): graph, block, i = position_key", "for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1,", "a dictionary of call # points to this func which", "def validate(self): \"\"\"Check that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances()", "raise TypeError('Variable or Constant expected, got %r' % (arg,)) def", "can be in three states: # * block not in", "in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry #", "for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None:", "# input variables). #print '* processblock', block, cells self.annotated[block] =", "= len(flowgraph.getargs()) assert len(inputcells) == nbarg # wrong number of", "graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value)", "v_out, v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out", "the return variables of all graphs is annotated if self.added_blocks", "for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype is", "cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] = (graph,", "end of debugging information --- self.frozen = False if policy", "try: pos = self.bookkeeper.position_key except AttributeError: pos = '?' if", "else: knowntypedata = {} for link in exits: constraints =", "op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell =", "as e: # note that UnionError is a subclass e.source", "link in block.exits if link.exitcase is not None] elif e.op.opname", "results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg): \"Gives the SomeValue", "# which it is fine to always raise an exception.", "= SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue:", "graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint()", "= operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return", "% (arg,)) def binding(self, arg): \"Gives the SomeValue corresponding to", "and set their type args_s = [self.typeannotation(t) for t in", "is known exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch =", "point into block with the given input cells.\"\"\" if graph", "* self.annotated[block] == False: # the input variables of the", "by # an exception handler. We then only follow the", "s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] =", "of a block. assert len(block.inputargs) == len(inputcells) for a, cell", "block in self.notify: # reflow from certain positions when this", "assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell to op.result", "= opindex def __repr__(self): if not self.break_at: break_at = \"?\"", "failed, hopefully temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as", "several phases: calling # a graph that has already been", "until we find we must generalize the # input variables).", "flowgraph, inputs_s = self.get_call_parameters(function, args_s, policy) if main_entry_point: self.translator.entry_point_graph =", "return repr(graph) + blk + opid def flowin(self, graph, block):", "block, cells): \"\"\"Register an entry point into block with the", "function's input arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current)", "self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___", "= pair(s_out, s_constraint).improve() # ignore links that try to pass", "assert block in self.annotated self.annotated[block] = False # must re-flow", "link.exitcase is not None] elif e.op.opname in ('simple_call', 'call_args', 'next'):", "= '?' if pos != '?': pos = self.whereami(pos) log.WARNING(\"%s/", "from rpython.tool.error import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable,", "s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index = position_key self.reflowpendingblock(graph,", "if pos is None: try: pos = self.bookkeeper.position_key except AttributeError:", "this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if", "constraints.items(): new_vs = renaming.get(v, []) for new_v in new_vs: renamed_knowntypedata[value][new_v]", "# get the (current) return value v = graph.getreturnvar() try:", "None self.op = op self.opindex = opindex def __repr__(self): if", "v_input in zip(link.args, link.target.inputargs): if v_out == v_last_exc_type: s_out =", "= prevpolicy def annotate_helper(self, function, args_s, policy=None): if policy is", "flow object space. These are the operations for # which", "if s_arg is None: raise KeyError return s_arg def typeannotation(self,", "reflowpendingblock(self, graph, block): assert not self.frozen assert graph not in", "that it should try to progress elsewhere.\"\"\" def __init__(self, annotator,", "so far. # (some functions actually never do, they always", "the new 'cells' with each of the block's existing input", "= defaultdict(list) for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for", "= True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return", "if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that", "renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs): if v_out ==", "s_out == s_ImpossibleValue: ignore_link = True s_out = self.apply_renaming(s_out, renaming)", "entry point into block with the given input cells.\"\"\" if", "all of them for block in newblocks: for op in", "text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text) for graph", "the BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container().", "in self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs", "block.operations[i] with self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops", "self.complete() return self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type", "operations! for a, s_newarg in zip(block.inputargs, cells): s_oldarg = self.binding(a)", "we must redo the analysis if unions != oldcells: self.bindinputargs(graph,", "cells) else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] =", "in violations of the # more general results invariant: e.g.", "exceptional # branches. exits = [link for link in block.exits", "log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for annotator.bookkeeper _______", "the operations for # which it is fine to always", "for callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback", "the known type of a control flow graph variable, defaulting", "for v, s in constraints.items(): new_vs = renaming.get(v, []) for", "block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata = {} for link in", "not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells)", "{} # set of blocks already seen self.added_blocks = None", "<filename>rpython/annotator/annrpython.py from __future__ import absolute_import import types from collections import", "exits = block.exits if isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if", "block of this graph has been analysed. callpositions = self.notify.setdefault(graph.returnblock,", "# this is the case where the last operation of", "a block can be in three states: # * block", "__repr__(self): if not self.break_at: break_at = \"?\" else: break_at =", "the input args of a block. assert len(block.inputargs) == len(inputcells)", "constraints: s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore", "= \"\" if block: at = block.at() if at: blk", "rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy = policy", "isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind resultcell", "# still have to consider all the operations in the", "the last operation of the block will # always raise", "link in exits if link.exitcase == s_exitswitch.const] if block.canraise: op", "None: # interface for tests from rpython.translator.translator import TranslationContext translator", "elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype", "block.inputargs] try: unions = [annmodel.unionof(c1,c2) for c1, c2 in zip(oldcells,inputcells)]", "op.result def get_exception(self, operation): \"\"\" Return the annotation for all", "is not called recursively. # self.flowin() can only issue calls", "block.raising_op: # this is the case where the last operation", "self.whereami(pos) log.WARNING(\"%s/ %s\" % (pos, msg)) #___ interface for annotator.bookkeeper", "or Constant expected, got %r' % (arg,)) def binding(self, arg):", "dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs = self.translator.graphs", "gather_error(self, graph, block, i) raise else: # dead code removal:", "that `operation` may raise. \"\"\" can_only_throw = operation.get_can_only_throw(self) if can_only_throw", "following information is recorded for debugging --- self.blocked_graphs = {}", "has side effects if translator is None: # interface for", "again self.blocked_blocks = {} # set of {blocked_block: (graph, index)}", "types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy()", "and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value if isinstance(v_last_exc_value, Variable):", "class BlockedInference(Exception): \"\"\"This exception signals the type inference engine that", "s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper from rpython.rtyper.normalizecalls", "# let's be careful about avoiding propagated SomeImpossibleValues # to", "while i < len(block.operations): op = block.operations[i] with self.bookkeeper.at_position((graph, block,", "in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if", "follow all exits if the exitswitch # is known exits", "newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const s_out =", "BlockedInference as e: if e.op is block.raising_op: # this is", "if v_out in constraints: s_constraint = constraints[v_out] s_out = pair(s_out,", "high-level interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively", "= self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not", "[] for v in s_out.is_type_of: renamed_is_type_of += renaming[v] assert s_out.knowntype", "opid = \" op=%d\" % i return repr(graph) + blk", "%s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value, s_old)) assert False", "op = new_ops[0] self.consider_op(op) i += 1 except BlockedInference as", "of a block can be in three states: # *", "blocks are partially annotated if op.result.annotation is None: break #", "= graph.getreturnvar() try: return self.binding(v) except KeyError: # the function", "nbarg # wrong number of args # register the entry", "= self.__dict__.copy() for key, value in ret.items(): if key not", "# graph -- it's already low-level operations! for a, s_newarg", "operation of the block will # always raise an exception", "_______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph,", "else: # dead code removal: don't follow all exits if", "return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph,", "isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else:", "seen the block. # * self.annotated[block] == False: # the", "annmodel.UnionError as e: # Add source code to the UnionError", "desc = self.bookkeeper.getdesc(function) prevpolicy = self.policy self.policy = policy self.bookkeeper.enter(None)", "recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index", "bindings for the input args of a block. assert len(block.inputargs)", "op # some blocks are partially annotated if op.result.annotation is", "corresponding to the given Variable or Constant.\" if isinstance(arg, Variable):", "blocks # --- end of debugging information --- self.frozen =", "if block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph,", "function, args_s, policy=None): if policy is None: from rpython.annotator.policy import", "into block with the given input cells.\"\"\" if graph in", "renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of += renaming[v]", "-- in the assert of setbinding() for arg in op.args:", "# dead code removal: don't follow all exits if the", "'is_type_of'): renamed_is_type_of = [] for v in s_out.is_type_of: renamed_is_type_of +=", "sync # with the flow object space. These are the", "inputs_s.append(s_out) if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s)", "statement so far. # (some functions actually never do, they", "'cells' with each of the block's existing input # variables.", "result in violations of the # more general results invariant:", "the input variables of the block have bindings but we", "else: self.mergeinputargs(graph, block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph", "# hack for debug tools only if not hasattr(e, '__annotator_block'):", "= new_ops if not new_ops: continue new_ops[-1].result = op.result op", "and v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable):", "information --- self.frozen = False if policy is None: from", "annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self, msg,", "import absolute_import import types from collections import defaultdict from rpython.tool.ansi_print", "s_old)) assert False arg.annotation = s_value def warning(self, msg, pos=None):", "block. # * self.annotated[block] == graph-containing-block: # analysis done (at", "inputcells): if isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag", "is None: # interface for tests from rpython.translator.translator import TranslationContext", "Constant): return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if", "graphs = {} for block in block_subset: graph = self.annotated.get(block)", "bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper def __getstate__(self): attrs =", "constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link", "a reflow whenever the # return block of this graph", "\"\" if block: at = block.at() if at: blk =", "graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check", "in three states: # * block not in self.annotated: #", "if at: blk = \" block\"+at opid=\"\" if i is", "of all graphs is annotated if self.added_blocks is not None:", "note that UnionError is a subclass e.source = gather_error(self, graph,", "variables). #print '* processblock', block, cells self.annotated[block] = graph if", "* self.annotated[block] == graph-containing-block: # analysis done (at least until", "False in newgraphs else: newgraphs = self.translator.graphs #all of them", "(graph, None) def mergeinputargs(self, graph, block, inputcells): # Merge the", "analysis if unions != oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self,", "link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException))", "# Merge the new 'cells' with each of the block's", "return type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable:", "e.op.opname in ('simple_call', 'call_args', 'next'): # XXX warning, keep the", "policy if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper =", "followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {}", "signals the type inference engine that the situation is currently", "entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import", "False # must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self,", "UnionError e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise # if", "self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells,", "Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {}) else: knowntypedata =", "rpython.annlowlevel to # detect which are the new blocks that", "that!\" from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # make", "self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not self.frozen", "tuple): self.reflowfromposition(callback) # callback is a position else: callback() def", "rpython.rtyper.extfuncregistry # has side effects if translator is None: #", "never do, they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self,", "isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op, -1) resultcell = op.consider(self) if", "to self.addpendingblock(). # The analysis of a block can be", "self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\" %(break_at, self.op) __str__ =", "to the given Variable or Constant.\" s_arg = self.annotation(arg) if", "test_annotate_iter_empty_container(). return else: # other cases are problematic (but will", "i)): new_ops = op.transform(self) if new_ops is not None: block.operations[i:i+1]", "bookkeeper frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value", "graph, block, inputcells): # Create the initial bindings for the", "e.source = '\\n'.join(source_lines(graph, block, None, long=True)) raise # if the", "(isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type and v_last_exc_value", "for new_v in new_vs: renamed_knowntypedata[value][new_v] = s assert isinstance(s_out, annmodel.SomeBool)", "= False inputs_s = [] renaming = defaultdict(list) for v_out,", "for v_out, v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input", "self.setbinding(v, s_ImpossibleValue) def validate(self): \"\"\"Check that the annotation results are", "SystemExit() raise annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar()", "= position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks if", "# set of {blocked_block: (graph, index)} # --- the following", "if block_subset is None: perform_normalizations(self) #___ flowing annotations in blocks", "self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self, policy): saved", "assert isinstance(resultcell, annmodel.SomeObject) assert isinstance(op.result, Variable) self.setbinding(op.result, resultcell) # bind", "in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a", "is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This", "operation.get_can_only_throw(self) if can_only_throw is None: return SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw)", "s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return object", "to op.result def get_exception(self, operation): \"\"\" Return the annotation for", "knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block in self.notify: #", "knowntypedata = {} for link in exits: constraints = knowntypedata.get(link.exitcase,", "newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key): graph, block, i", "(isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link = False inputs_s", "graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks", "v_out in link.args: s_out = self.annotation(v_out) if v_out in constraints:", "newblocks = self.annotated # all of them for block in", "graph in self.fixed_graphs: # special case for annotating/rtyping in several", "self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'):", "self.follow_link(graph, link, {}) continue if s_exception == s_ImpossibleValue: break s_case", "except AttributeError: pos = '?' if pos != '?': pos", "op = block.raising_op s_exception = self.get_exception(op) for link in exits:", "for arg in op.args: if isinstance(self.annotation(arg), annmodel.SomeImpossibleValue): raise BlockedInference(self, op,", "for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks = saved", "set of {blocked_block: (graph, index)} # --- the following information", "= {} # set of graphs that have blocked blocks", "= {} return ret #___ convenience high-level interface __________________ def", "SomeBool(const=False) ... # boom -- in the assert of setbinding()", "else: if isinstance(block.exitswitch, Variable): knowntypedata = getattr( block.exitswitch.annotation, \"knowntypedata\", {})", "return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type inference", "position_key): graph, block, index = position_key self.reflowpendingblock(graph, block) def call_sites(self):", "func which triggers a reflow whenever the # return block", "assert isinstance(function, types.FunctionType), \"fix that!\" from rpython.annotator.policy import AnnotatorPolicy policy", "exits if link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op", "annmodel.AnnotatorError(text) for graph in newgraphs: v = graph.getreturnvar() if v.annotation", "return s_variable.knowntype else: return object else: raise TypeError(\"Variable or Constant", "self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until none is", "annotator.bookkeeper _______ def recursivecall(self, graph, whence, inputcells): if isinstance(whence, tuple):", "is None: perform_normalizations(self) #___ flowing annotations in blocks _____________________ def", "\"\"\"Register an entry point into block with the given input", "the annotation for all exceptions that `operation` may raise. \"\"\"", "inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out)", "and that's it. # About 'next': see test_annotate_iter_empty_container(). return else:", "def gettype(self, variable): \"\"\"Return the known type of a control", "index = position_key self.reflowpendingblock(graph, block) def call_sites(self): newblocks = self.added_blocks", "resultcell) # bind resultcell to op.result def get_exception(self, operation): \"\"\"", "raise an exception which is immediately caught by # an", "not called recursively. # self.flowin() can only issue calls to", "inputs_s = [] renaming = defaultdict(list) for v_out, v_input in", "newgraphs else: newgraphs = self.translator.graphs #all of them got_blocked_blocks =", "renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v in", "'__annotator_block'): setattr(e, '__annotator_block', block) raise # The dict 'added_blocks' is", "they always raise exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph,", "if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def", "of a control flow graph variable, defaulting to 'object'.\"\"\" if", "c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: # Add source", "= position_key blk = \"\" if block: at = block.at()", "link.last_exc_value assert (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) assert v_last_exc_type", "intersection(s_exception, s_case) if s_matching_exc != s_ImpossibleValue: self.follow_raise_link(graph, link, s_matching_exc) s_exception", "op, -1) # the operation cannot succeed assert isinstance(resultcell, annmodel.SomeObject)", "interface __________________ def build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build", "is block.raising_op: # this is the case where the last", "def addpendingblock(self, graph, block, cells): \"\"\"Register an entry point into", "build_types(self, function, input_arg_types, complete_now=True, main_entry_point=False): \"\"\"Recursively build annotations about the", "= False # must re-flow self.blocked_blocks[block] = (graph, None) def", "are passed in, and don't annotate the old # graph", "for op in block.operations: if op.opname in ('simple_call', 'call_args'): yield", "tuple): parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index", "assert not (isinstance(link.exitcase, (types.ClassType, type)) and issubclass(link.exitcase, BaseException)) ignore_link =", "self.bookkeeper.enter(None) try: return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def", "about the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\"", "Exception as e: # hack for debug tools only if", "for block in block_subset: graph = self.annotated.get(block) if graph: graphs[graph]", "given Variable or Constant.\" s_arg = self.annotation(arg) if s_arg is", "v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args,", "def binding(self, arg): \"Gives the SomeValue corresponding to the given", "doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has", "the block will # always raise an exception which is", "= v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out,", "block.canraise: op = block.raising_op s_exception = self.get_exception(op) for link in", "def __init__(self, annotator, op, opindex): self.annotator = annotator try: self.break_at", "AttributeError: pos = '?' if pos != '?': pos =", "policy=None): if policy is None: from rpython.annotator.policy import AnnotatorPolicy policy", "from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype", "type args_s = [self.typeannotation(t) for t in input_arg_types] # XXX", "helper creates. if self.added_blocks is not None: self.added_blocks[block] = True", "self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None self.op =", "binding(self, arg): \"Gives the SomeValue corresponding to the given Variable", "self.addpendinggraph(flowgraph, inputcells) # recursively proceed until no more pending block", "each of the block's existing input # variables. oldcells =", "block, cells) if not self.annotated[block]: self.pendingblocks[block] = graph def complete_pending_blocks(self):", "return self.binding(v) except KeyError: # the function didn't reach any", "annotating/rtyping in several phases: calling # a graph that has", "blocked, and that it should try to progress elsewhere.\"\"\" def", "self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value])) inputs_s = []", "== len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise annmodel.AnnotatorError(text)", "new_ops[0] self.consider_op(op) i += 1 except BlockedInference as e: if", "s_out.knowntype is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const =", "for c1, c2 in zip(oldcells,inputcells)] except annmodel.UnionError as e: #", "Merge the new 'cells' with each of the block's existing", "-> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ... #", "link.exitcase if case is None: self.follow_link(graph, link, {}) continue if", "len(block.inputargs) == len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a,", "return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self,", "len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise SystemExit() raise", "# Important: this is not called recursively. # self.flowin() can", "link.exitcase == s_exitswitch.const] if block.canraise: op = block.raising_op s_exception =", "arg.annotation if s_old is not None: if not s_value.contains(s_old): log.WARNING(\"%s", "else: # other cases are problematic (but will hopefully be", "= TranslationContext() translator.annotator = self self.translator = translator self.pendingblocks =", "partially annotated if op.result.annotation is None: break # ignore the", "True s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) if ignore_link: return self.links_followed[link]", "situation is currently blocked, and that it should try to", "block) def complete(self): \"\"\"Process pending blocks until none is left.\"\"\"", "ret[key] = {} return ret #___ convenience high-level interface __________________", "'call_args'): yield op # some blocks are partially annotated if", "self.annotated: # never seen the block. # * self.annotated[block] ==", "if graph: graphs[graph] = True for graph in graphs: simplify.eliminate_empty_blocks(graph)", "AnnotatorPolicy() else: self.policy = policy if bookkeeper is None: bookkeeper", "with the flow object space. These are the operations for", "Variable or Constant.\" s_arg = self.annotation(arg) if s_arg is None:", "self.added_blocks = saved def build_graph_types(self, flowgraph, inputcells, complete_now=True): checkgraph(flowgraph) nbarg", "self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def follow_raise_link(self, graph, link,", "to this func which triggers a reflow whenever the #", "annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert not self.frozen if block", "== s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot", "translator is None: # interface for tests from rpython.translator.translator import", "SomeInstance(self.bookkeeper.getuniqueclassdef(Exception)) else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the", "bookkeeper def __getstate__(self): attrs = \"\"\"translator pendingblocks annotated links_followed notify", "UnionError is a subclass e.source = gather_error(self, graph, block, i)", "been followed self.notify = {} # {block: {positions-to-reflow-from-when-done}} self.fixed_graphs =", "inputcells) # get the (current) return value v = graph.getreturnvar()", "graph, block): # Important: this is not called recursively. #", "whenever the # return block of this graph has been", "v = graph.getreturnvar() if v.annotation is None: self.setbinding(v, s_ImpossibleValue) def", "self.translator.update_call_graph(parent_graph, graph, tag) # self.notify[graph.returnblock] is a dictionary of call", "block, i) raise else: # dead code removal: don't follow", "always raise an exception which is immediately caught by #", "up to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked:", "else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link]", "v_last_exc_value if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type,", "s_arg = self.annotation(arg) if s_arg is None: raise KeyError return", "import (format_blocked_annotation_error, gather_error, source_lines) from rpython.flowspace.model import Variable, Constant, checkgraph", "if isinstance(v_last_exc_value, Variable): self.setbinding(v_last_exc_value, s_last_exc_value) if isinstance(v_last_exc_type, Variable): self.setbinding(v_last_exc_type, typeof([v_last_exc_value]))", "complete_now=True): checkgraph(flowgraph) nbarg = len(flowgraph.getargs()) assert len(inputcells) == nbarg #", "import rpython.rtyper.extfuncregistry # has side effects if translator is None:", "== nbarg # wrong number of args # register the", "return object else: raise TypeError(\"Variable or Constant instance expected, \"", "s in constraints.items(): new_vs = renaming.get(v, []) for new_v in", "( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from rpython.annotator.bookkeeper import Bookkeeper", "% annmodel.unionof(s_value, s_old)) assert False arg.annotation = s_value def warning(self,", "ret.items(): if key not in attrs: assert type(value) is dict,", "# an exception handler. We then only follow the exceptional", "continue if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc", "type(variable.value) elif isinstance(variable, Variable): s_variable = variable.annotation if s_variable: return", "model as annmodel, signature from rpython.annotator.model import ( typeof, s_ImpossibleValue,", "len(inputcells) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell) self.annotated[block]", "we find we must generalize the # input variables). #print", "s_out = self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out]", "= translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated", "the exitswitch # is known exits = block.exits if isinstance(block.exitswitch,", "variables of all graphs is annotated if self.added_blocks is not", "None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block): assert not", "in the block. # * self.annotated[block] == graph-containing-block: # analysis", "= newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata = {} for value,", "def whereami(self, position_key): graph, block, i = position_key blk =", "if v_out == v_last_exc_type: s_out = typeof(renaming[v_last_exc_value]) if isinstance(v_last_exc_type, Constant):", "\"?\" else: break_at = self.annotator.whereami(self.break_at) return \"<BlockedInference break_at %s [%s]>\"", "simplifications for the new blocks self.simplify(block_subset=self.added_blocks) finally: self.policy, self.added_blocks =", "cases are problematic (but will hopefully be solved # later", "class RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\"", "False] assert len(blocked_blocks) == len(self.blocked_blocks) text = format_blocked_annotation_error(self, self.blocked_blocks) #raise", "rpython.annotator import model as annmodel, signature from rpython.annotator.model import (", "self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations", "renaming[v_out].append(v_input) for v_out in link.args: s_out = self.annotation(v_out) if v_out", "self.annotation(v_out) if v_out in constraints: s_constraint = constraints[v_out] s_out =", "frozen policy added_blocks\"\"\".split() ret = self.__dict__.copy() for key, value in", "Create the initial bindings for the input args of a", "block) except BlockedInference as e: self.annotated[block] = False # failed,", "small helper creates. if self.added_blocks is not None: self.added_blocks[block] =", "False # must re-flow self.blocked_blocks[block] = (graph, None) def bindinputargs(self,", "to enter an op; the latter can result in violations", "# interface for tests from rpython.translator.translator import TranslationContext translator =", "self.pendingblocks: break # finished # make sure that the return", "moved elsewhere?) _______ def simplify(self, block_subset=None, extra_passes=None): # Generic simplifications", "tools only if not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise", "as e: # hack for debug tools only if not", "in block_subset: graph = self.annotated.get(block) if graph: graphs[graph] = True", "tag) # self.notify[graph.returnblock] is a dictionary of call # points", "!= oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if", "proceed until no more pending block is left if complete_now:", "cells.\"\"\" if graph in self.fixed_graphs: # special case for annotating/rtyping", "RPythonAnnotator(object): \"\"\"Block annotator for RPython. See description in doc/translation.txt.\"\"\" def", "does not contain %s\" % (s_value, s_old)) log.WARNING(\"%s\" % annmodel.unionof(s_value,", "isinstance(whence, tuple): parent_graph, parent_block, parent_index = whence tag = parent_block,", "None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result =", "flowgraph, inputcells): self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells):", "{} for block in block_subset: graph = self.annotated.get(block) if graph:", "to # processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return", "not None: if not s_value.contains(s_old): log.WARNING(\"%s does not contain %s\"", "collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import", "been rtyped. Safety-check the new # annotations that are passed", "self.added_blocks] newgraphs = dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else:", "the given Variable or Constant.\" s_arg = self.annotation(arg) if s_arg", "{}) else: knowntypedata = {} for link in exits: constraints", "call_sites(self): newblocks = self.added_blocks if newblocks is None: newblocks =", "v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out = self.apply_renaming(s_out, renaming)", "not in attrs: assert type(value) is dict, ( \"%r is", "renamed_is_type_of += renaming[v] assert s_out.knowntype is type newcell = typeof(renamed_is_type_of)", "not self.frozen assert graph not in self.fixed_graphs self.pendingblocks[block] = graph", "We then only follow the exceptional # branches. exits =", "see processblock() below self.links_followed = {} # set of links", "# ignore the unannotated part #___ simplification (should be moved", "except annmodel.HarmlesslyBlocked: return except annmodel.AnnotatorError as e: # note that", "self.__dict__.copy() for key, value in ret.items(): if key not in", "policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now)", "bookkeeper=None): import rpython.rtyper.extfuncregistry # has side effects if translator is", "block in self.blocked_blocks: del self.blocked_blocks[block] try: self.flowin(graph, block) except BlockedInference", "policy): saved = self.policy, self.added_blocks self.policy = policy try: self.added_blocks", "None: raise KeyError return s_arg def typeannotation(self, t): return signature.annotation(t,", "rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul", "* block not in self.annotated: # never seen the block.", "if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool #", "= self.pendingblocks.popitem() self.processblock(graph, block) def complete(self): \"\"\"Process pending blocks until", "block) def call_sites(self): newblocks = self.added_blocks if newblocks is None:", "self.consider_op(op) i += 1 except BlockedInference as e: if e.op", "not in self.annotated: # never seen the block. # *", "def __init__(self, translator=None, policy=None, bookkeeper=None): import rpython.rtyper.extfuncregistry # has side", "annotate the old # graph -- it's already low-level operations!", "dict. please update %s.__getstate__\" % (key, self.__class__.__name__)) ret[key] = {}", "= self self.translator = translator self.pendingblocks = {} # map", "latter can result in violations of the # more general", "ClassDefs.\"\"\" return self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph,", "isinstance(block.exitswitch, Variable): s_exitswitch = self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link", "if ignore_link: return self.links_followed[link] = True self.addpendingblock(graph, link.target, inputs_s) def", "= s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1)", "# recursively proceed until no more pending block is left", "self.annotated # all of them for block in newblocks: for", "actually never do, they always raise exceptions) return s_ImpossibleValue def", "# later by reflowing). Throw the BlockedInference up to #", "object else: raise TypeError(\"Variable or Constant instance expected, \" \"got", "True self.addpendingblock(graph, link.target, inputs_s) #___ creating the annotations based on", "translator self.pendingblocks = {} # map {block: graph-containing-it} self.annotated =", "== s_oldarg else: assert not self.frozen if block not in", "s_ImpossibleValue: raise BlockedInference(self, op, -1) # the operation cannot succeed", "code removal: don't follow all exits if the exitswitch #", "= whence callpositions[callback] = True # generalize the function's input", "positions when this block is done for callback in self.notify[block]:", "is not None: self.added_blocks[block] = True def reflowpendingblock(self, graph, block):", "been analysed. callpositions = self.notify.setdefault(graph.returnblock, {}) if whence is not", "an exception handler. We then only follow the exceptional #", "pending blocks until none is left.\"\"\" while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self)", "the given Variable or Constant.\" if isinstance(arg, Variable): return arg.annotation", "# if the merged cells changed, we must redo the", "find we must generalize the # input variables). #print '*", "= flowgraph return self.build_graph_types(flowgraph, inputs_s, complete_now=complete_now) def get_call_parameters(self, function, args_s,", "operations in the block. # * self.annotated[block] == graph-containing-block: #", "self.pendingblocks = {} # map {block: graph-containing-it} self.annotated = {}", "new_ops is not None: block.operations[i:i+1] = new_ops if not new_ops:", "None: resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self,", "unannotated part #___ simplification (should be moved elsewhere?) _______ def", "cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else:", "expected, \" \"got %r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a", "as e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block]", "self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in exits", "inputs_s) def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value", "resultcell = op.consider(self) if resultcell is None: resultcell = s_ImpossibleValue", "is a dictionary of call # points to this func", "for link in exits: case = link.exitcase if case is", "cells): \"\"\"Register an entry point into block with the given", "self.frozen if block not in self.annotated: self.bindinputargs(graph, block, cells) else:", "'next'): # XXX warning, keep the name of the call", "v_input in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out in link.args: s_out", "= s_out.const s_out = newcell if hasattr(s_out, 'knowntypedata'): renamed_knowntypedata =", "case for annotating/rtyping in several phases: calling # a graph", "= self.added_blocks if newblocks is None: newblocks = self.annotated #", "if graph in self.fixed_graphs: # special case for annotating/rtyping in", "= None # see processblock() below self.links_followed = {} #", "self.setbinding(a, cell) self.annotated[block] = False # must flowin. self.blocked_blocks[block] =", "addpendingblock(self, graph, block, cells): \"\"\"Register an entry point into block", "return except annmodel.AnnotatorError as e: # note that UnionError is", "case where the last operation of the block will #", "def follow_link(self, graph, link, constraints): assert not (isinstance(link.exitcase, (types.ClassType, type))", "for key, value in ret.items(): if key not in attrs:", "self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block, cells) if not", "types from collections import defaultdict from rpython.tool.ansi_print import AnsiLogger from", "analysis done (at least until we find we must generalize", "def warning(self, msg, pos=None): if pos is None: try: pos", "in ret.items(): if key not in attrs: assert type(value) is", "block, cells self.annotated[block] = graph if block in self.blocked_blocks: del", "None, long=True)) raise # if the merged cells changed, we", "exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph, link, constraints) if block", "functions actually never do, they always raise exceptions) return s_ImpossibleValue", "return desc.get_call_parameters(args_s) finally: self.bookkeeper.leave() self.policy = prevpolicy def annotate_helper(self, function,", "s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc = intersection(s_exception,", "v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out) s_out", "BlockedInference and that's it. # About 'next': see test_annotate_iter_empty_container(). return", "resultcell = s_ImpossibleValue elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op,", "self.translator = translator self.pendingblocks = {} # map {block: graph-containing-it}", "None: from rpython.annotator.policy import AnnotatorPolicy self.policy = AnnotatorPolicy() else: self.policy", "old # graph -- it's already low-level operations! for a,", "= block.raising_op s_exception = self.get_exception(op) for link in exits: case", "new 'cells' with each of the block's existing input #", "set their type args_s = [self.typeannotation(t) for t in input_arg_types]", "if done is False] assert len(blocked_blocks) == len(self.blocked_blocks) text =", "oldcells: self.bindinputargs(graph, block, unions) def apply_renaming(self, s_out, renaming): if hasattr(s_out,", "i += 1 except BlockedInference as e: if e.op is", "is annotated if self.added_blocks is not None: newgraphs = [self.annotated[block]", "operations for # which it is fine to always raise", "in link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint", "args_s, policy) self.build_graph_types(graph, inputcells, complete_now=False) self.complete_helpers(policy) return graph def complete_helpers(self,", "links that have ever been followed self.notify = {} #", "exceptions) return s_ImpossibleValue def reflowfromposition(self, position_key): graph, block, index =", "Constant.\" s_arg = self.annotation(arg) if s_arg is None: raise KeyError", "op=%d\" % i return repr(graph) + blk + opid def", "propagated SomeImpossibleValues # to enter an op; the latter can", "to # detect which are the new blocks that annotating", "= [self.typeannotation(t) for t in input_arg_types] # XXX hack annmodel.TLS.check_str_without_nul", "block not in self.annotated: self.bindinputargs(graph, block, cells) else: self.mergeinputargs(graph, block,", "triggers a reflow whenever the # return block of this", "self.op = op self.opindex = opindex def __repr__(self): if not", "and don't annotate the old # graph -- it's already", "s_out.const s_out = newcell s_out.set_knowntypedata(renamed_knowntypedata) return s_out def whereami(self, position_key):", "isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or Constant expected,", "simplify.eliminate_empty_blocks(graph) self.bookkeeper.compute_at_fixpoint() if block_subset is None: perform_normalizations(self) #___ flowing annotations", "e: self.annotated[block] = False # failed, hopefully temporarily self.blocked_blocks[block] =", "= dict.fromkeys(newgraphs) got_blocked_blocks = False in newgraphs else: newgraphs =", "else: return self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type", "temporarily self.blocked_blocks[block] = (graph, e.opindex) except Exception as e: #", "from rpython.annotator.model import ( typeof, s_ImpossibleValue, SomeInstance, intersection, difference) from", "link, {}) continue if s_exception == s_ImpossibleValue: break s_case =", "% (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\" return", "import AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul =", "redo the analysis if unions != oldcells: self.bindinputargs(graph, block, unions)", "SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) -> SomeBool # is_(SomeInstance(not", "call operations in sync # with the flow object space.", "invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None) ->", "corresponding to the given Variable or Constant.\" s_arg = self.annotation(arg)", "apply_renaming(self, s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for", "more pending block is left if complete_now: self.complete() return self.annotation(flowgraph.getreturnvar())", "where the last operation of the block will # always", "be solved # later by reflowing). Throw the BlockedInference up", "s_exception = self.get_exception(op) for link in exits: case = link.exitcase", "graph assert block in self.annotated self.annotated[block] = False # must", "import defaultdict from rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair", "value in ret.items(): if key not in attrs: assert type(value)", "creates. if self.added_blocks is not None: self.added_blocks[block] = True def", "main_entry_point=False): \"\"\"Recursively build annotations about the specific entry point.\"\"\" assert", "elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out = self.annotation(v_out)", "zip(block.inputargs, cells): s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg", "op): # let's be careful about avoiding propagated SomeImpossibleValues #", "graph that has already been rtyped. Safety-check the new #", "block, i = position_key blk = \"\" if block: at", "#all of them got_blocked_blocks = False in self.annotated.values() if got_blocked_blocks:", "continue new_ops[-1].result = op.result op = new_ops[0] self.consider_op(op) i +=", "SomeImpossibleValues # to enter an op; the latter can result", "block's existing input # variables. oldcells = [self.binding(a) for a", "of the # more general results invariant: e.g. if SomeImpossibleValue", "'knowntypedata'): renamed_knowntypedata = {} for value, constraints in s_out.knowntypedata.items(): renamed_knowntypedata[value]", "{}) self.follow_link(graph, link, constraints) if block in self.notify: # reflow", "KeyError return s_arg def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def", "None) -> SomeBool # is_(SomeInstance(not None), None) -> SomeBool(const=False) ...", "def follow_raise_link(self, graph, link, s_last_exc_value): v_last_exc_type = link.last_exception v_last_exc_value =", "name of the call operations in sync # with the", "in self.blocked_graphs.values(): self.blocked_graphs[graph] = True blocked_blocks = [block for block,", "until no more pending block is left if complete_now: self.complete()", "block. # * self.annotated[block] == False: # the input variables", "= AnnotatorPolicy() else: self.policy = policy if bookkeeper is None:", "that the annotation results are valid\"\"\" self.bookkeeper.check_no_flags_on_instances() def annotation(self, arg):", "= self.binding(block.exitswitch) if s_exitswitch.is_constant(): exits = [link for link in", "a graph that has already been rtyped. Safety-check the new", "recursively proceed until no more pending block is left if", "gettype(self, variable): \"\"\"Return the known type of a control flow", "{block: graph-containing-it} self.annotated = {} # set of blocks already", "{block: {positions-to-reflow-from-when-done}} self.fixed_graphs = {} # set of graphs not", "\"\"\"Process pending blocks until none is left.\"\"\" while True: self.complete_pending_blocks()", "must flowin. self.blocked_blocks[block] = (graph, None) def mergeinputargs(self, graph, block,", "to consider all the operations in the block. # *", "# * self.annotated[block] == False: # the input variables of", "the # input variables). #print '* processblock', block, cells self.annotated[block]", "= gather_error(self, graph, block, i) raise else: # dead code", "all exits if the exitswitch # is known exits =", "pair(s_out, s_constraint).improve() # ignore links that try to pass impossible", "while self.pendingblocks: block, graph = self.pendingblocks.popitem() self.processblock(graph, block) def complete(self):", "policy is None: from rpython.annotator.policy import AnnotatorPolicy policy = AnnotatorPolicy()", "s assert isinstance(s_out, annmodel.SomeBool) newcell = annmodel.SomeBool() if s_out.is_constant(): newcell.const", "except AttributeError: self.break_at = None self.op = op self.opindex =", "additional # small helper creates. if self.added_blocks is not None:", "whence is not None: if callable(whence): def callback(): whence(self, graph)", "AnnotatorPolicy policy = AnnotatorPolicy() # XXX hack annmodel.TLS.check_str_without_nul = (", "self.bookkeeper.new_exception(can_only_throw) class BlockedInference(Exception): \"\"\"This exception signals the type inference engine", "if not self.break_at: break_at = \"?\" else: break_at = self.annotator.whereami(self.break_at)", "variables of the block have bindings but we # still", "graph not in self.fixed_graphs self.pendingblocks[block] = graph assert block in", "in zip(link.args, link.target.inputargs): renaming[v_out].append(v_input) for v_out, v_input in zip(link.args, link.target.inputargs):", "def typeannotation(self, t): return signature.annotation(t, self.bookkeeper) def setbinding(self, arg, s_value):", "if policy is None: from rpython.annotator.policy import AnnotatorPolicy self.policy =", "if s_out.is_constant(): newcell.const = s_out.const s_out = newcell if hasattr(s_out,", "# The dict 'added_blocks' is used by rpython.annlowlevel to #", "variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant): return type(variable.value) elif", "None) def bindinputargs(self, graph, block, inputcells): # Create the initial", "s_out, renaming): if hasattr(s_out, 'is_type_of'): renamed_is_type_of = [] for v", "link.args: s_out = self.annotation(v_out) if v_out in constraints: s_constraint =", "for link in exits if link.exitcase == s_exitswitch.const] if block.canraise:", "this is the case where the last operation of the", "not None: block.operations[i:i+1] = new_ops if not new_ops: continue new_ops[-1].result", "Variable): s_variable = variable.annotation if s_variable: return s_variable.knowntype else: return", "= [self.binding(a) for a in block.inputargs] try: unions = [annmodel.unionof(c1,c2)", "BaseException)) ignore_link = False inputs_s = [] renaming = defaultdict(list)", "v_last_exc_type.value elif v_last_exc_type.annotation.is_constant(): s_out.const = v_last_exc_type.annotation.const inputs_s.append(s_out) else: s_out =", "self.addpendingblock(flowgraph, flowgraph.startblock, inputcells) def addpendingblock(self, graph, block, cells): \"\"\"Register an", "graph, block, i = position_key blk = \"\" if block:", "self.bookkeeper.at_position((graph, block, i)): new_ops = op.transform(self) if new_ops is not", "elif resultcell == s_ImpossibleValue: raise BlockedInference(self, op, -1) # the", "s_out = self.apply_renaming(s_out, renaming) inputs_s.append(s_out) self.links_followed[link] = True self.addpendingblock(graph, link.target,", "if bookkeeper is None: bookkeeper = Bookkeeper(self) self.bookkeeper = bookkeeper", "space. These are the operations for # which it is", "side effects if translator is None: # interface for tests", "dict 'added_blocks' is used by rpython.annlowlevel to # detect which", "points to this func which triggers a reflow whenever the", "# bind resultcell to op.result def get_exception(self, operation): \"\"\" Return", "self.blocked_graphs[graph] = True blocked_blocks = [block for block, done in", "block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs else:", "{} for link in exits: constraints = knowntypedata.get(link.exitcase, {}) self.follow_link(graph,", "ignore links that try to pass impossible values if s_out", "which are the new blocks that annotating an additional #", "existing input # variables. oldcells = [self.binding(a) for a in", "parent_graph, parent_block, parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph,", "rpython.tool.ansi_print import AnsiLogger from rpython.tool.pairtype import pair from rpython.tool.error import", "if s_exception == s_ImpossibleValue: break s_case = SomeInstance(self.bookkeeper.getuniqueclassdef(case)) s_matching_exc =", "# never seen the block. # * self.annotated[block] == False:", "self.bookkeeper.classdefs #___ medium-level interface ____________________________ def addpendinggraph(self, flowgraph, inputcells): self.addpendingblock(flowgraph,", "is type newcell = typeof(renamed_is_type_of) if s_out.is_constant(): newcell.const = s_out.const", "self.get_exception(op) for link in exits: case = link.exitcase if case", "callable(whence): def callback(): whence(self, graph) else: callback = whence callpositions[callback]", "annotator for RPython. See description in doc/translation.txt.\"\"\" def __init__(self, translator=None,", "exitswitch # is known exits = block.exits if isinstance(block.exitswitch, Variable):", "{} # map {block: graph-containing-it} self.annotated = {} # set", "# callback is a position else: callback() def follow_link(self, graph,", "results invariant: e.g. if SomeImpossibleValue enters is_ # is_(SomeImpossibleValue, None)", "consider_op(self, op): # let's be careful about avoiding propagated SomeImpossibleValues", "s_oldarg = self.binding(a) assert annmodel.unionof(s_oldarg, s_newarg) == s_oldarg else: assert", "annotation(self, arg): \"Gives the SomeValue corresponding to the given Variable", "known type of a control flow graph variable, defaulting to", "the specific entry point.\"\"\" assert isinstance(function, types.FunctionType), \"fix that!\" from", "args_s, policy) if main_entry_point: self.translator.entry_point_graph = flowgraph return self.build_graph_types(flowgraph, inputs_s,", "= link.exitcase if case is None: self.follow_link(graph, link, {}) continue", "annotator try: self.break_at = annotator.bookkeeper.position_key except AttributeError: self.break_at = None", "callback in self.notify[block]: if isinstance(callback, tuple): self.reflowfromposition(callback) # callback is", "arg.annotation elif isinstance(arg, Constant): return self.bookkeeper.immutablevalue(arg.value) else: raise TypeError('Variable or", "i return repr(graph) + blk + opid def flowin(self, graph,", "assert False arg.annotation = s_value def warning(self, msg, pos=None): if", "the latter can result in violations of the # more", "\"\"\"translator pendingblocks annotated links_followed notify bookkeeper frozen policy added_blocks\"\"\".split() ret", "arguments self.addpendingblock(graph, graph.startblock, inputcells) # get the (current) return value", "# processblock(). e.opindex = i raise except annmodel.HarmlesslyBlocked: return except", "Throw the BlockedInference up to # processblock(). e.opindex = i", "# points to this func which triggers a reflow whenever", "not in self.fixed_graphs self.pendingblocks[block] = graph assert block in self.annotated", "control flow graph variable, defaulting to 'object'.\"\"\" if isinstance(variable, Constant):", "inputcells): # Merge the new 'cells' with each of the", "while True: self.complete_pending_blocks() self.policy.no_more_blocks_to_annotate(self) if not self.pendingblocks: break # finished", "s_exception = difference(s_exception, s_case) else: if isinstance(block.exitswitch, Variable): knowntypedata =", "= False in newgraphs else: newgraphs = self.translator.graphs #all of", "%r\" % (variable,)) def getuserclassdefinitions(self): \"\"\"Return a list of ClassDefs.\"\"\"", "with each of the block's existing input # variables. oldcells", "isinstance(callback, tuple): self.reflowfromposition(callback) # callback is a position else: callback()", "type of a control flow graph variable, defaulting to 'object'.\"\"\"", "transform.transform_graph(self, block_subset=block_subset, extra_passes=extra_passes) if block_subset is None: graphs = self.translator.graphs", "position else: callback() def follow_link(self, graph, link, constraints): assert not", "self.annotation(flowgraph.getreturnvar()) def gettype(self, variable): \"\"\"Return the known type of a", "{blocked_block: (graph, index)} # --- the following information is recorded", "msg, pos=None): if pos is None: try: pos = self.bookkeeper.position_key", "flowin(self, graph, block): try: i = 0 while i <", "s_constraint = constraints[v_out] s_out = pair(s_out, s_constraint).improve() # ignore links", "parent_index = whence tag = parent_block, parent_index self.translator.update_call_graph(parent_graph, graph, tag)", "# special case for annotating/rtyping in several phases: calling #", "See description in doc/translation.txt.\"\"\" def __init__(self, translator=None, policy=None, bookkeeper=None): import", "if not self.pendingblocks: break # finished # make sure that", "input args of a block. assert len(block.inputargs) == len(inputcells) for", "# the function didn't reach any return statement so far.", "None: opid = \" op=%d\" % i return repr(graph) +" ]
[ "= url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str", "combiner. :type inherited: bool :param is_contribution: A value indicating if", "inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str", "= { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name',", "self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param", "'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key':", "'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'},", "label self.order = order self.overridden = overridden self.visible = visible", "'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'},", "metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution =", ":type is_contribution: bool :param label: Label for the field :type", "'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name',", "description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id", "it inherits from :type inherits: str :param is_disabled: :type is_disabled:", "inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract", "visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param", "Section(Model): \"\"\"Section. :param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>`", "= id self.inherits = inherits self.is_disabled = is_disabled self.layout =", ":param url: :type url: str \"\"\" _attribute_map = { 'id':", "{'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden':", ":class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution. :type", "str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type", "self.class_ = class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id", "= hidden self.id = id self.name = name self.order =", "\"\"\" _attribute_map = { 'color': {'key': 'color', 'type': 'str'}, 'hidden':", "inherited: bool :param is_contribution: A value indicating if the layout", "{'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None,", "node is contribution are not. :type is_contribution: bool :param label:", ":class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout node.", "self.condition_type = condition_type self.field = field self.value = value class", "to only be only set by the combiner. :type inherited:", "id: str :param inherits: Parent WIT Id/Internal ReferenceName that it", "indicating whether this layout node has been overridden by a", ":param is_contribution: A value indicating if the layout node is", "color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior,", "parent_process_type_id: str :param version: :type version: str \"\"\" _attribute_map =", "{'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None):", "'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}", "super(ProcessModel, self).__init__() self.description = description self.name = name self.projects =", ":param id: :type id: str :param inherits: Parent WIT Id/Internal", "class Group(Model): \"\"\"Group. :param contribution: Contribution for the group. :type", "name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name =", "reference_name: :type reference_name: str :param type_id: :type type_id: str \"\"\"", "FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param id: :type", "is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id", "node has been inherited from a parent layout. This is", "'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key':", ":param id: :type id: str \"\"\" _attribute_map = { 'id':", "if the layout node is contribution are not. :type is_contribution:", "super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_ self.color =", "url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of", "str :param height: The height for the contribution. :type height:", "of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the", "overridden by a child layout. :type overridden: bool :param read_only:", "} def __init__(self, id=None): super(Extension, self).__init__() self.id = id class", "name: :type name: str :param type: :type type: object :param", "'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'},", "= { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType',", "'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key':", "'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'},", "'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None,", "overridden=None): super(Section, self).__init__() self.groups = groups self.id = id self.overridden", "the layout node is contribution or not. :type is_contribution: bool", "'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, description=None, name=None,", "-------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", ":type icon: str :param id: :type id: str :param inherits:", "self.conditions = conditions self.friendly_name = friendly_name self.id = id self.is_disabled", "watermark: Watermark text for the textbox. :type watermark: str \"\"\"", "bool :param color: :type color: str :param description: :type description:", "__init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description", "= icon self.id = id self.inherits = inherits self.is_disabled =", "'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key':", "Order in which the group should appear in the section.", "child layout. :type overridden: bool :param visible: A value indicating", "'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}", "'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order',", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None,", ":class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id: :type", "is_default: bool :param is_enabled: :type is_enabled: bool :param name: :type", "self).__init__() self.contribution = contribution self.controls = controls self.height = height", ":type contribution_id: str :param height: The height for the contribution.", "= id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str", "object :param color: :type color: str :param description: :type description:", "contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type", "url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param", ":type is_default: bool :param is_enabled: :type is_enabled: bool :param name:", "inputs: dict :param show_on_deleted_work_item: A value indicating if the contribution", "int :param overridden: A value indicating whether this layout node", "Height of the control, for html controls. :type height: int", "indicating if the page should be hidden or not. :type", "'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'},", "{'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id':", ":param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url:", "'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type':", "self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param", "icon: str :param id: :type id: str :param inherits: Parent", "= overridden self.read_only = read_only self.visible = visible self.watermark =", "overridden by a child layout. :type overridden: bool :param visible:", "= projects self.properties = properties self.reference_name = reference_name self.type_id =", "whether any user operations are permitted on this page and", "Control(Model): \"\"\"Control. :param contribution: Contribution for the control. :type contribution:", "value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param", "self.description = description self.id = id self.name = name self.url", "'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution,", "'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url',", "is_contribution: A value indicating if the layout node is contribution", ":type description: str :param id: :type id: str :param name:", "id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None):", "'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} } def __init__(self,", "'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type':", "order: :type order: int :param overridden: A value indicating whether", "'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None,", "is_system: :type is_system: bool \"\"\" _attribute_map = { 'actions': {'key':", "WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden: :type", "condition_type: str :param field: :type field: str :param value: :type", ":type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id:", "'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'},", "{'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id':", "{'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name':", "= action_type self.target_field = target_field self.value = value class RuleConditionModel(Model):", "= is_identity self.name = name self.type = type self.url =", ":type metadata: str :param order: :type order: int :param overridden:", ":type description: str :param name: :type name: str :param projects:", "'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type':", "'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self,", "should be hidden or not. :type visible: bool :param watermark:", "'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None,", ":type id: str :param is_identity: :type is_identity: bool :param name:", "page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id =", "def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description =", ":param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id:", "'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self,", "\"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id':", "id: The id for the layout node. :type id: str", "'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order',", "of the control, for html controls. :type height: int :param", "Gets and sets extensions list :type extensions: list of :class:`Extension", "order self.overridden = overridden self.visible = visible class Page(Model): \"\"\"Page.", "'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'},", "'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, action_type=None,", "{'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category':", "overridden self.page_type = page_type self.sections = sections self.visible = visible", "hidden: :type hidden: bool :param id: :type id: str :param", "{'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon':", "'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior", "name self.overriden = overriden self.rank = rank self.url = url", "'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type',", ":class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type control_type:", "{'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls':", "{'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden':", "'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'}", ":param action_type: :type action_type: str :param target_field: :type target_field: str", "id: :type id: str :param inherits: Parent WIT Id/Internal ReferenceName", "self).__init__() self.behaviors = behaviors self.class_ = class_ self.color = color", "height: Height of the control, for html controls. :type height:", "{ 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type':", "show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type':", "value indicating whether this layout node has been overridden by", "id: :type id: str :param is_disabled: :type is_disabled: bool :param", "self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for", "'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__()", "'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__()", "<work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout. :type system_controls:", "self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param", "value indicating whether any user operations are permitted on this", "\"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'id':", "{'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only':", "= label self.order = order self.overridden = overridden self.visible =", "class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param is_default:", "and the contents of this page :type locked: bool :param", "= { 'id': {'key': 'id', 'type': 'str'} } def __init__(self,", "{'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} }", "= type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object", ":type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions:", "Watermark text for the textbox. :type watermark: str \"\"\" _attribute_map", "def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type", "The label for the page. :type label: str :param locked:", "url: str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type':", "= type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions:", "str :param version: :type version: str \"\"\" _attribute_map = {", "is_disabled: :type is_disabled: bool :param is_system: :type is_system: bool \"\"\"", "'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None,", "the contribution should be show on deleted workItem. :type show_on_deleted_work_item:", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None,", "Label for the group. :type label: str :param order: Order", "'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__()", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits',", "name self.order = order self.state_category = state_category self.url = url", "'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'},", "<work-item-tracking.v4_0.models.Group>` :param id: The id for the layout node. :type", "id self.inherits = inherits self.is_disabled = is_disabled self.layout = layout", "Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id:", "for the contribution. :type contribution_id: str :param height: The height", "{'key': 'url', 'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference,", "self.page_type = page_type self.sections = sections self.visible = visible class", "'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None):", "{'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} }", "super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions self.friendly_name =", "parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\"", "= url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference", "{'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled':", ":param version: :type version: str \"\"\" _attribute_map = { 'class_':", "is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type", "= contribution self.controls = controls self.height = height self.id =", "'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'},", "'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}", "= label self.metadata = metadata self.order = order self.overridden =", ":param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name:", "conditions self.friendly_name = friendly_name self.id = id self.is_disabled = is_disabled", "layout node is contribution are not. :type is_contribution: bool :param", ":class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url: :type", "'value': {'key': 'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None,", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type':", "'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def", "is_system: bool \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type':", "not. :type visible: bool \"\"\" _attribute_map = { 'contribution': {'key':", "'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}", "'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}", "the contribution. :type contribution_id: str :param height: The height for", "visible: bool :param watermark: Watermark text for the textbox. :type", "height for the contribution. :type height: int :param id: The", "name: str :param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>`", "{ 'description': {'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type':", "are not. :type is_contribution: bool :param label: The label for", "Top level tabs of the layout. :type pages: list of", "'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key':", "{'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value':", "__init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description", "int :param id: The id for the layout node. :type", "'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name',", "that it inherits from :type inherits: str :param is_disabled: :type", "self.height = height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class", "str :param locked: A value indicating whether any user operations", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, id=None,", "'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def", "version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param", "inherits from :type inherits: str :param is_disabled: :type is_disabled: bool", "'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states',", "= target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type:", "url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color self.description", ":param label: The label for the page. :type label: str", "self.contribution = contribution self.controls = controls self.height = height self.id", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type':", "self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description:", "self.type = type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param", "version: :type version: str \"\"\" _attribute_map = { 'class_': {'key':", "'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type':", "indicating if the control should be hidden or not. :type", ":class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id: :type", "'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def", "= is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id:", "The id for the contribution. :type contribution_id: str :param height:", "'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden',", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, id=None, url=None):", "{'key': 'name', 'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None,", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, abstract=None, color=None,", "inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors =", "class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param", "height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height =", "bool :param visible: A value indicating if the group should", "_attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name': {'key':", "'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'},", ":type name: str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name:", "abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None):", "'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__()", "'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'},", "'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'},", "'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'},", "'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key':", ":type overridden: bool :param page_type: The icon for the page.", "self.layout = layout self.name = name self.states = states self.url", ":type description: str :param icon: :type icon: str :param id:", "= { 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault',", "= contribution self.control_type = control_type self.height = height self.id =", "height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior.", "self.class_ = class_ self.color = color self.description = description self.icon", "height: int :param id: The id for the layout node.", "state_category: str :param url: :type url: str \"\"\" _attribute_map =", "appear in the section. :type order: int :param overridden: A", "page. :type page_type: object :param sections: The sections of the", "value indicating if the layout node is contribution are not.", "'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls',", ":param field: :type field: str :param value: :type value: str", "\"\"\"FieldModel. :param description: :type description: str :param id: :type id:", "self).__init__() self.abstract = abstract self.color = color self.description = description", "{'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects':", "'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'},", "'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self,", "self.overridden = overridden self.visible = visible class Page(Model): \"\"\"Page. :param", "name: :type name: str :param order: :type order: int :param", "level tabs of the layout. :type pages: list of :class:`Page", "action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field =", "WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url: :type", "super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default self.url =", "should be show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\"", "= behavior_field_id self.id = id self.url = url class WorkItemBehaviorReference(Model):", "contribution or not. :type is_contribution: bool :param label: Label for", "html controls. :type height: int :param id: The id for", "'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'},", "_attribute_map = { 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key':", "str :param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param", "is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version = version", "'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'}", "str :param description: :type description: str :param fields: :type fields:", "bool :param url: :type url: str \"\"\" _attribute_map = {", "'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type':", "'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id',", "'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField,", "self).__init__() self.description = description self.name = name self.projects = projects", "if the contribution should be show on deleted workItem. :type", "= name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for", "{'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} }", "been overridden by a child layout. :type overridden: bool :param", "\"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages':", "overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls = controls", "'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory',", "= order self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model):", "self).__init__() self.extensions = extensions self.pages = pages self.system_controls = system_controls", "'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'},", "'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None,", ":type id: str :param name: :type name: str :param url:", "class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id:", ":param contribution_id: The id for the contribution. :type contribution_id: str", "{'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden':", "{'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields':", "<work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden: :type overriden:", "description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description =", "\"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param", "not. :type is_contribution: bool :param label: Label for the field", "= { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field',", "control_type: Type of the control. :type control_type: str :param height:", "states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type", "locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution =", "bool :param parent_process_type_id: :type parent_process_type_id: str :param version: :type version:", "behavior_field_id: :type behavior_field_id: str :param id: :type id: str :param", ":type id: str :param inherits: Parent WIT Id/Internal ReferenceName that", "str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'},", "layout. This is expected to only be only set by", ":param inherited: A value indicating whether this layout node has", "= system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for the", "'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'},", "CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param name: :type", "control. :type control_type: str :param height: Height of the control,", "ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param name: :type", "'url', 'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__()", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled',", "<work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id: :type type_id:", ":type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name',", "bool \"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'},", "self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version", "is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions self.friendly_name", "self.label = label self.metadata = metadata self.order = order self.overridden", "str :param order: Order in which the group should appear", "{'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None, inputs=None,", "self.behaviors = behaviors self.class_ = class_ self.color = color self.description", "license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT", "'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'},", "{'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color':", "been overridden by a child layout. :type overridden: bool \"\"\"", "super(Section, self).__init__() self.groups = groups self.id = id self.overridden =", "} def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None,", "= visible class Page(Model): \"\"\"Page. :param contribution: Contribution for the", "{'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked':", "super(Control, self).__init__() self.contribution = contribution self.control_type = control_type self.height =", "the control, for html controls. :type height: int :param id:", ":param target_field: :type target_field: str :param value: :type value: str", "_attribute_map = { 'id': {'key': 'id', 'type': 'str'} } def", ":type is_enabled: bool :param name: :type name: str \"\"\" _attribute_map", "def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description =", ":class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states: :type", "self.value = value class Section(Model): \"\"\"Section. :param groups: :type groups:", "{'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled':", "height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__()", "locked: A value indicating whether any user operations are permitted", "'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description',", "'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None,", "'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type':", "friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions", ":type color: str :param hidden: :type hidden: bool :param id:", "lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization", "self.pages = pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param", "} def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups =", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "{'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id':", "'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties,", "contribution are not. :type is_contribution: bool :param label: Label for", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type':", "groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for", "read_only: bool :param visible: A value indicating if the control", "behavior_field_id self.id = id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference.", "controls. :type height: int :param id: The id for the", "'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None,", ":param order: Order in which the page should appear in", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type':", "'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None,", "'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type", "metadata: str :param order: :type order: int :param overridden: A", "= version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str", ":type target_field: str :param value: :type value: str \"\"\" _attribute_map", "contribution. :type height: int :param inputs: A dictionary holding key", "'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key':", "value indicating if the group should be hidden or not.", "{ 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type':", "of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits:", "{'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden':", "'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type':", "url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param", "node. :type id: str :param overridden: A value indicating whether", "'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id',", "str :param reference_name: :type reference_name: str \"\"\" _attribute_map = {", "from msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution: Contribution", "control should be hidden or not. :type visible: bool :param", "'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible',", "'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key':", "'type': 'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id", "expected to only be only set by the combiner. :type", "page_type: object :param sections: The sections of the page. :type", "inherits: Parent WIT Id/Internal ReferenceName that it inherits from :type", "the section. :type order: int :param overridden: A value indicating", "is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default =", "pages: Top level tabs of the layout. :type pages: list", "self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_:", "is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name:", "'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None, type=None,", "\"\"\"ProcessProperties. :param class_: :type class_: object :param is_default: :type is_default:", "class Section(Model): \"\"\"Section. :param groups: :type groups: list of :class:`Group", "'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type':", "target_field: :type target_field: str :param value: :type value: str \"\"\"", ":type url: str \"\"\" _attribute_map = { 'id': {'key': 'id',", "\"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map = {", "'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key':", "\"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'} }", "'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height',", ":param parent_process_type_id: :type parent_process_type_id: str :param version: :type version: str", ":type name: str :param overriden: :type overriden: bool :param rank:", "description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__()", "indicating if the group should be hidden or not. :type", ":param description: :type description: str :param icon: :type icon: str", "{'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url':", ":type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param", "'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None, height=None,", "'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__()", "type_id: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None,", "= height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model):", "self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior:", "'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key':", "{ 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type':", ":param behavior_field_id: :type behavior_field_id: str :param id: :type id: str", "= parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id:", "value indicating if the control is readonly. :type read_only: bool", "{'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url':", "{'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system':", "id: str :param name: :type name: str :param url: :type", "{'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} }", "node has been overridden by a child layout. :type overridden:", "'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution',", "self.description = description self.id = id self.is_identity = is_identity self.name", "for the textbox. :type watermark: str \"\"\" _attribute_map = {", "bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'},", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None,", "contribution: Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param", "'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id',", "bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id:", ":type friendly_name: str :param id: :type id: str :param is_disabled:", "of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout.", "action_type self.target_field = target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel.", "'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self,", "= url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str", "system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages self.system_controls", ":param type_id: :type type_id: str \"\"\" _attribute_map = { 'description':", "self.inherits = inherits self.is_disabled = is_disabled self.layout = layout self.name", "super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field self.value =", "in the project root for license information. # -------------------------------------------------------------------------------------------- #", "value indicating whether this layout node has been inherited from", "'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key':", "'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'},", "} def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel,", ":type height: int :param id: The id for the layout", "str :param overriden: :type overriden: bool :param rank: :type rank:", "'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type':", "'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} } def __init__(self, groups=None,", "system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions':", "inputs: A dictionary holding key value pairs for contribution inputs.", "'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'},", "extensions self.pages = pages self.system_controls = system_controls class Group(Model): \"\"\"Group.", "id self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout.", "Licensed under the MIT License. See License.txt in the project", "list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of", "self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description:", "'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'},", "{'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url':", "label: str :param metadata: Inner text of the control. :type", "{'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits':", "reference_name: :type reference_name: str \"\"\" _attribute_map = { 'description': {'key':", "'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self,", "def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__()", "be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from", "class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field:", "'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled',", "description: :type description: str :param id: :type id: str :param", "parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type", "'[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type':", "{ 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type':", "name: :type name: str :param projects: :type projects: list of", "'type': 'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None, id=None,", "'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key':", "'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'}", "str :param is_default: :type is_default: bool :param is_enabled: :type is_enabled:", "WIT Id/Internal ReferenceName that it inherits from :type inherits: str", ":type read_only: bool :param visible: A value indicating if the", "'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key':", "behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool", "description self.id = id self.is_identity = is_identity self.name = name", "'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key':", "\"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default':", "= { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault',", "overridden: bool :param read_only: A value indicating if the control", "url: :type url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key':", "will be lost if the code is regenerated. # --------------------------------------------------------------------------------------------", "the textbox. :type watermark: str \"\"\" _attribute_map = { 'contribution':", ":param name: :type name: str :param type: :type type: object", "name: str :param order: :type order: int :param state_category: :type", "class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior", "super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden self.id =", "self.fields = fields self.id = id self.inherits = inherits self.name", ":param value: :type value: str \"\"\" _attribute_map = { 'action_type':", "-------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may", "= pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution:", "self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description:", "msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution: Contribution for", "class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str :param name:", "'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type':", "project root for license information. # -------------------------------------------------------------------------------------------- # Generated file,", "self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors:", "'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key':", "a child layout. :type overridden: bool :param visible: A value", "= { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id',", "is_disabled self.layout = layout self.name = name self.states = states", "'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None):", "inherited self.is_contribution = is_contribution self.label = label self.order = order", ":type url: str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract',", "{'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible':", "description: :type description: str :param icon: :type icon: str :param", "{'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id':", ":param contribution: Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>`", ":type version: str \"\"\" _attribute_map = { 'class_': {'key': 'class',", "contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in", "__init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description", "self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param", "'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None,", ":class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>`", ":param friendly_name: :type friendly_name: str :param id: :type id: str", "label: str :param order: Order in which the group should", "'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled',", "which the page should appear in the layout. :type order:", "= url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str", "str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'},", ":type hidden: bool :param id: :type id: str :param name:", "= contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item =", ":type is_default: bool :param url: :type url: str \"\"\" _attribute_map", ":param description: :type description: str :param name: :type name: str", "id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None):", "= class_ self.color = color self.description = description self.icon =", ":type overridden: bool :param visible: A value indicating if the", ":param state_category: :type state_category: str :param url: :type url: str", "'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type':", "state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type", ":param id: :type id: str :param is_disabled: :type is_disabled: bool", ":type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level", "= { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls',", "= overridden self.page_type = page_type self.sections = sections self.visible =", "= overridden self.visible = visible class Page(Model): \"\"\"Page. :param contribution:", "'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'},", "inherited self.is_contribution = is_contribution self.label = label self.locked = locked", "'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type':", "<work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout node. :type", "\"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id: :type id:", "str :param value: :type value: str \"\"\" _attribute_map = {", "value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field self.value", "'name': {'key': 'name', 'type': 'str'} } def __init__(self, description=None, is_default=None,", "parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name = name", "'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel,", "deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id':", "'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'},", "be show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map", "overriden: bool :param rank: :type rank: int :param url: :type", "{'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled':", "class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions list", "= inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract:", "'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "{'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id':", "self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class", ":type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put", "'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the", "A value indicating if the layout node is contribution or", "= { 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden',", "value indicating if the page should be hidden or not.", ":param control_type: Type of the control. :type control_type: str :param", "{'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} }", "str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'},", "id self.name = name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel.", "'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'},", "overridden self.visible = visible class Page(Model): \"\"\"Page. :param contribution: Contribution", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity',", "'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'},", "actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list", "value: str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type':", "License.txt in the project root for license information. # --------------------------------------------------------------------------------------------", "height: The height for the contribution. :type height: int :param", "Label for the field :type label: str :param metadata: Inner", "'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout',", "self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id", "'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name',", "sets extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param", "'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, color=None,", "UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param is_default: :type", "'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key':", "'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'},", "group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be", "= { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color',", "'bool'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior=None,", "inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden:", "url: str \"\"\" _attribute_map = { 'color': {'key': 'color', 'type':", "id: str :param inherited: A value indicating whether this layout", "'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key':", ":class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color: :type", ":param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties:", "str :param type_id: :type type_id: str \"\"\" _attribute_map = {", "<work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param", "\"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type':", "\"\"\"FormLayout. :param extensions: Gets and sets extensions list :type extensions:", "the control. :type metadata: str :param order: :type order: int", "id: :type id: str :param is_identity: :type is_identity: bool :param", "a child layout. :type overridden: bool :param page_type: The icon", "self).__init__() self.groups = groups self.id = id self.overridden = overridden", ":param label: Label for the field :type label: str :param", "page should appear in the layout. :type order: int :param", "'str'}, 'value': {'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None,", "= value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str", "self.metadata = metadata self.order = order self.overridden = overridden self.read_only", "id: :type id: str \"\"\" _attribute_map = { 'id': {'key':", "Order in which the page should appear in the layout.", "{'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited':", "{'key': 'id', 'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__()", ":type description: str :param name: :type name: str :param parent_process_type_id:", "\"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color':", "self.description = description self.name = name self.projects = projects self.properties", "the contribution. :type height: int :param id: The id for", "inputs. :type inputs: dict :param show_on_deleted_work_item: A value indicating if", "str :param url: :type url: str \"\"\" _attribute_map = {", "'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'},", "'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type':", "Parent WIT Id/Internal ReferenceName that it inherits from :type inherits:", "'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type':", "class Control(Model): \"\"\"Control. :param contribution: Contribution for the control. :type", "action_type: :type action_type: str :param target_field: :type target_field: str :param", "_attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key':", "= label self.locked = locked self.order = order self.overridden =", "'id': {'key': 'id', 'type': 'str'} } def __init__(self, id=None): super(Extension,", "sections: The sections of the page. :type sections: list of", "if the control should be hidden or not. :type visible:", "version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled", "self.locked = locked self.order = order self.overridden = overridden self.page_type", "\"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id':", "be hidden or not. :type visible: bool \"\"\" _attribute_map =", "self.id = id self.inherited = inherited self.is_contribution = is_contribution self.label", "group. :type label: str :param order: Order in which the", "{'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} }", "'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url',", "self.read_only = read_only self.visible = visible self.watermark = watermark class", ":type name: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'},", "contribution self.id = id self.inherited = inherited self.is_contribution = is_contribution", "str :param name: :type name: str :param projects: :type projects:", "'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type':", "the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls:", "inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height", "dict :param show_on_deleted_work_item: A value indicating if the contribution should", "'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def", "} def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id", "'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key':", "= control_type self.height = height self.id = id self.inherited =", "'description', 'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key':", "'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type':", "Headers controls of the layout. :type system_controls: list of :class:`Control", "fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type", "self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description:", "'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}", "id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution", "bool :param label: Label for the group. :type label: str", "'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'}", "'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key':", "= url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str", "system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution for the group.", ":param reference_name: :type reference_name: str :param type_id: :type type_id: str", "inherits: str :param is_disabled: :type is_disabled: bool :param layout: :type", "'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order',", "is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default", "id self.name = name self.order = order self.state_category = state_category", "is readonly. :type read_only: bool :param visible: A value indicating", "url: :type url: str \"\"\" _attribute_map = { 'id': {'key':", ":type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls", "name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "= behavior self.is_default = is_default self.url = url class WorkItemTypeModel(Model):", "'[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type':", "'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def", "friendly_name: :type friendly_name: str :param id: :type id: str :param", "url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>`", "is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference.", "contribution_id: str :param height: The height for the contribution. :type", "for contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A value", "Changes may cause incorrect behavior and will be lost if", "= is_contribution self.label = label self.order = order self.overridden =", "{'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None, url=None):", "def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions", "<work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution. :type height:", ":param id: :type id: str :param url: :type url: str", "def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id", ":class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type':", "'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type':", "regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control.", "value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field self.value", "if the group should be hidden or not. :type visible:", "super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled =", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order',", "str :param id: :type id: str :param is_identity: :type is_identity:", "value: :type value: str \"\"\" _attribute_map = { 'action_type': {'key':", "'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key':", "self).__init__() self.actions = actions self.conditions = conditions self.friendly_name = friendly_name", "url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type':", "description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default", "workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key':", "to be put in the group. :type controls: list of", "is_contribution self.label = label self.order = order self.overridden = overridden", "'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key':", "the layout. :type order: int :param overridden: A value indicating", "} def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel,", "'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'},", "{ 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type':", "MIT License. See License.txt in the project root for license", "__init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None,", "self).__init__() self.condition_type = condition_type self.field = field self.value = value", "is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param version: :type", "= conditions self.friendly_name = friendly_name self.id = id self.is_disabled =", "'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key':", "controls of the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>`", "label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls", "of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color:", ":param url: :type url: str \"\"\" _attribute_map = { 'description':", "is_enabled: bool :param name: :type name: str \"\"\" _attribute_map =", "{'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description':", "type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param", "'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def", ":param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions:", "file, DO NOT EDIT # Changes may cause incorrect behavior", "<work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'},", "# -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control. :param", "layout node has been inherited from a parent layout. This", "{'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None,", "order: int :param state_category: :type state_category: str :param url: :type", "RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field: :type", "self.is_contribution = is_contribution self.label = label self.locked = locked self.order", ":type inherited: bool :param is_contribution: A value indicating if the", "metadata: Inner text of the control. :type metadata: str :param", "name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type", "bool \"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'},", ":type order: int :param overridden: A value indicating whether this", "holding key value pairs for contribution inputs. :type inputs: dict", "'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id = id", "= inherited self.is_contribution = is_contribution self.label = label self.order =", "'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type':", "the page should appear in the layout. :type order: int", "'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key':", "on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map = {", "= layout self.name = name self.states = states self.url =", "'str'}, 'type_id': {'key': 'typeId', 'type': 'str'} } def __init__(self, description=None,", "'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups", "super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url =", "All rights reserved. # Licensed under the MIT License. See", "'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key':", "url: :type url: str \"\"\" _attribute_map = { 'behaviors': {'key':", "'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None,", "= { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id',", ":param read_only: A value indicating if the control is readonly.", "layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map =", "'overridden', 'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section,", "<work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control. :type control_type: str", "'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type':", "name: :type name: str :param url: :type url: str \"\"\"", "'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'},", "is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool :param", "inputs self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type", "def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None,", "__init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field", ":class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map =", "{'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name':", "FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>`", "= visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description:", "str :param field: :type field: str :param value: :type value:", "self.contribution = contribution self.id = id self.inherited = inherited self.is_contribution", "for the page. :type label: str :param locked: A value", "sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating", "'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type':", "str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'},", "'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key':", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects',", "'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type':", "bool :param read_only: A value indicating if the control is", ":type id: str :param name: :type name: str :param order:", "'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key': 'states', 'type':", "contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None,", "int :param url: :type url: str \"\"\" _attribute_map = {", ":type is_contribution: bool :param label: The label for the page.", "description: str :param name: :type name: str :param projects: :type", "color self.description = description self.icon = icon self.id = id", "= color self.description = description self.icon = icon self.id =", "projects self.properties = properties self.reference_name = reference_name self.type_id = type_id", "url: str \"\"\" _attribute_map = { 'abstract': {'key': 'abstract', 'type':", "Id/Internal ReferenceName that it inherits from :type inherits: str :param", "self.id = id self.inherits = inherits self.name = name self.overriden", "overridden: A value indicating whether this layout node has been", "'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} } def", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type':", "self.name = name self.order = order self.state_category = state_category self.url", "{ 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type':", "the field :type label: str :param metadata: Inner text of", "'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type': 'bool'},", "visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type = control_type", "the control is readonly. :type read_only: bool :param visible: A", "id for the layout node. :type id: str :param inherited:", "color: str :param description: :type description: str :param fields: :type", "in which the page should appear in the layout. :type", "indicating if the contribution should be show on deleted workItem.", "indicating whether any user operations are permitted on this page", "name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden", "is_default: :type is_default: bool :param url: :type url: str \"\"\"", "DO NOT EDIT # Changes may cause incorrect behavior and", "# -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes", "'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__()", "this layout node has been overridden by a child layout.", "'type': 'str'} } def __init__(self, color=None, hidden=None, id=None, name=None, order=None,", "= overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str", "ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type class_: object :param is_default: :type", "Model class Control(Model): \"\"\"Control. :param contribution: Contribution for the control.", "visible: A value indicating if the group should be hidden", "= { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id',", "class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden:", "friendly_name self.id = id self.is_disabled = is_disabled self.is_system = is_system", "'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self,", "control_type self.height = height self.id = id self.inherited = inherited", "order self.overridden = overridden self.read_only = read_only self.visible = visible", "{'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} }", ":class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the layout.", "self.inherits = inherits self.name = name self.overriden = overriden self.rank", "str :param inherited: A value indicating whether this layout node", "self.actions = actions self.conditions = conditions self.friendly_name = friendly_name self.id", "'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type':", "'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type': 'str'},", "rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color", "self).__init__() self.contribution = contribution self.id = id self.inherited = inherited", "overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color =", "self.is_enabled = is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param", "'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type':", "'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType',", "self.inherited = inherited self.is_contribution = is_contribution self.label = label self.locked", ":type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value", "'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "hidden self.id = id self.name = name self.order = order", "overridden by a child layout. :type overridden: bool :param page_type:", "self).__init__() self.description = description self.name = name self.parent_process_type_id = parent_process_type_id", "self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id: :type id:", "whether this layout node has been inherited from a parent", "'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key':", "int :param state_category: :type state_category: str :param url: :type url:", "the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height:", "behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object", "{'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height':", "bool :param id: :type id: str :param name: :type name:", "should be hidden or not. :type visible: bool \"\"\" _attribute_map", ":param color: :type color: str :param description: :type description: str", "{'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None,", "'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None,", "= description self.fields = fields self.id = id self.inherits =", "{'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} }", "order: Order in which the group should appear in the", "__init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field", "def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel,", ":param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default:", "= groups self.id = id self.overridden = overridden class UpdateProcessModel(Model):", "self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param", "= order self.overridden = overridden self.visible = visible class Page(Model):", "'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'},", ":param order: Order in which the group should appear in", "id: str :param is_disabled: :type is_disabled: bool :param is_system: :type", "'type': 'object'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description',", "id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id =", "indicating if the control is readonly. :type read_only: bool :param", "'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key':", "condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field =", ":param description: :type description: str :param is_default: :type is_default: bool", "<work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in the group.", "id: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type':", ":type is_contribution: bool :param label: Label for the group. :type", "def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups", "information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT #", "} def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions =", "'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'},", "'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'} } def __init__(self,", ":type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height", "'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type':", "} def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior =", ":type inputs: dict :param show_on_deleted_work_item: A value indicating if the", "indicating whether this layout node has been inherited from a", "watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param", "__init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description = description", "WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color: :type", "{ 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type':", "self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type color:", "super(Page, self).__init__() self.contribution = contribution self.id = id self.inherited =", "'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type':", "Microsoft Corporation. All rights reserved. # Licensed under the MIT", "'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def", "description: :type description: str :param is_default: :type is_default: bool :param", "self.name = name self.overriden = overriden self.rank = rank self.url", "visible=None): super(Group, self).__init__() self.contribution = contribution self.controls = controls self.height", "'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key':", "page and the contents of this page :type locked: bool", "'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color',", "{ 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type':", "for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type", "permitted on this page and the contents of this page", "self.inherited = inherited self.is_contribution = is_contribution self.label = label self.order", "super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field self.value =", "{'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order':", "'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key':", "= overriden self.rank = rank self.url = url class WorkItemBehaviorField(Model):", "self).__init__() self.id = id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel.", "{'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name':", "'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'},", "parent layout. This is expected to only be only set", "id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors", "layout node. :type id: str :param overridden: A value indicating", "__init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id", "for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls", "in the layout. :type order: int :param overridden: A value", "color: str :param hidden: :type hidden: bool :param id: :type", "user operations are permitted on this page and the contents", "class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_", "url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param", ":param metadata: Inner text of the control. :type metadata: str", "'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key':", "'[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None,", "= is_default self.is_enabled = is_enabled self.name = name class WitContribution(Model):", "__init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id", "projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties", "'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type':", "{'key': 'watermark', 'type': 'str'} } def __init__(self, contribution=None, control_type=None, height=None,", "layout. :type overridden: bool \"\"\" _attribute_map = { 'groups': {'key':", "height self.id = id self.inherited = inherited self.is_contribution = is_contribution", "id: :type id: str :param url: :type url: str \"\"\"", ":param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name:", "def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None,", "See License.txt in the project root for license information. #", ":type abstract: bool :param color: :type color: str :param description:", "which the group should appear in the section. :type order:", "str :param order: :type order: int :param state_category: :type state_category:", "= { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField',", "class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str :param name:", "url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of", "{'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled':", "id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract =", "self.overriden = overriden self.rank = rank self.url = url class", ":type is_disabled: bool :param is_system: :type is_system: bool \"\"\" _attribute_map", "'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type':", "def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url", "= visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type description: str", "'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key':", "for the contribution. :type height: int :param inputs: A dictionary", "'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}", "order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution self.controls =", "= parent_process_type_id self.version = version class ProjectReference(Model): \"\"\"ProjectReference. :param description:", "'[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions", "= abstract self.color = color self.description = description self.fields =", ":param is_system: :type is_system: bool \"\"\" _attribute_map = { 'actions':", "{'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label':", "\"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url: :type url:", "<work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states: :type states:", "id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param", "class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param is_default:", "= is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version =", "value: str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type':", "order: int :param overridden: A value indicating whether this layout", "{'key': 'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark':", "page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for", "= { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class',", ":param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id:", "contribution. :type contribution_id: str :param height: The height for the", "'type': 'bool'} } def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None,", "if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import", "parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param id: :type", ":type name: str :param url: :type url: str \"\"\" _attribute_map", ":param inputs: A dictionary holding key value pairs for contribution", "list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param", "indicating if the layout node is contribution or not. :type", ":class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the layout. :type", "# Changes may cause incorrect behavior and will be lost", ":type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name:", "{'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity':", "for html controls. :type height: int :param id: The id", "icon for the page. :type page_type: object :param sections: The", "= extensions self.pages = pages self.system_controls = system_controls class Group(Model):", "'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key':", "'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None,", "# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "= actions self.conditions = conditions self.friendly_name = friendly_name self.id =", "label for the page. :type label: str :param locked: A", "class_: :type class_: object :param is_default: :type is_default: bool :param", "id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name:", "icon: :type icon: str :param id: :type id: str :param", "self.id = id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param", "'type': 'bool'} } def __init__(self, groups=None, id=None, overridden=None): super(Section, self).__init__()", "{'key': 'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden':", "id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id = id", "name: :type name: str :param overriden: :type overriden: bool :param", "This is expected to only be only set by the", "name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the", ":param rank: :type rank: int :param url: :type url: str", "'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None,", "is_identity self.name = name self.type = type self.url = url", "\"\"\"ProjectReference. :param description: :type description: str :param id: :type id:", ":type description: str :param fields: :type fields: list of :class:`WorkItemBehaviorField", "Generated file, DO NOT EDIT # Changes may cause incorrect", "'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key': 'id',", "self).__init__() self.color = color self.hidden = hidden self.id = id", "'color', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key':", "def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None,", ":param color: :type color: str :param hidden: :type hidden: bool", "name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description", "the control. :type control_type: str :param height: Height of the", "{ 'id': {'key': 'id', 'type': 'str'} } def __init__(self, id=None):", "locked: bool :param order: Order in which the page should", "color: :type color: str :param description: :type description: str :param", "'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type':", "object :param url: :type url: str \"\"\" _attribute_map = {", "'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type':", ":type url: str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors',", "the contents of this page :type locked: bool :param order:", "Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type:", "EDIT # Changes may cause incorrect behavior and will be", "id: str :param overridden: A value indicating whether this layout", "__init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None,", "= inherited self.is_contribution = is_contribution self.label = label self.metadata =", "name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id =", "for the group. :type label: str :param order: Order in", "the layout node. :type id: str :param inherited: A value", "WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default:", "{'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url':", "id: str :param url: :type url: str \"\"\" _attribute_map =", "{'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None,", "self.order = order self.overridden = overridden self.read_only = read_only self.visible", "color self.hidden = hidden self.id = id self.name = name", "'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type':", "{'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height':", "{'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name':", "bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type", ":param is_enabled: :type is_enabled: bool :param name: :type name: str", "{'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} }", "control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None,", "self.properties = properties self.reference_name = reference_name self.type_id = type_id class", "properties self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties.", "hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color =", "'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id =", "'contribution', 'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key':", "= is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions:", "of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id:", "'type': 'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url',", "this page :type locked: bool :param order: Order in which", "version: str \"\"\" _attribute_map = { 'class_': {'key': 'class', 'type':", "is_contribution: bool :param label: Label for the group. :type label:", "_attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls': {'key':", "} def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None,", "The icon for the page. :type page_type: object :param sections:", "'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__()", "if the layout node is contribution or not. :type is_contribution:", "{'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} }", "'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName',", "'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly',", "order: :type order: int :param state_category: :type state_category: str :param", "'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden',", "str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'},", "super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages self.system_controls =", "'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'},", "by a child layout. :type overridden: bool :param visible: A", "The height for the contribution. :type height: int :param id:", "def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior", "bool :param is_contribution: A value indicating if the layout node", "field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type self.field = field", "self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id:", ":param name: :type name: str :param order: :type order: int", ":type visible: bool :param watermark: Watermark text for the textbox.", "str :param id: :type id: str :param name: :type name:", "def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type = condition_type", "= field self.value = value class Section(Model): \"\"\"Section. :param groups:", "type_id: :type type_id: str \"\"\" _attribute_map = { 'description': {'key':", "'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type':", ":param description: :type description: str :param id: :type id: str", "of this page :type locked: bool :param order: Order in", "self.id = id self.name = name self.order = order self.state_category", "str \"\"\" _attribute_map = { 'color': {'key': 'color', 'type': 'str'},", "= is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class ProjectReference(Model):", "'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type':", "self.overridden = overridden self.page_type = page_type self.sections = sections self.visible", "{'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} }", "'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits',", "\"\"\" _attribute_map = { 'class_': {'key': 'class', 'type': 'object'}, 'is_default':", "str :param id: :type id: str :param is_disabled: :type is_disabled:", "is contribution or not. :type is_contribution: bool :param label: Label", "\"\"\"ProcessModel. :param description: :type description: str :param name: :type name:", "overridden: bool :param page_type: The icon for the page. :type", "class_: object :param is_default: :type is_default: bool :param is_enabled: :type", "bool :param is_system: :type is_system: bool \"\"\" _attribute_map = {", "str :param hidden: :type hidden: bool :param id: :type id:", "A value indicating whether this layout node has been overridden", "url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden self.id", "label self.metadata = metadata self.order = order self.overridden = overridden", "type: :type type: object :param url: :type url: str \"\"\"", ":param class_: :type class_: object :param is_default: :type is_default: bool", "Page(Model): \"\"\"Page. :param contribution: Contribution for the page. :type contribution:", "description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name", "str :param description: :type description: str :param icon: :type icon:", ":type inherits: str :param is_disabled: :type is_disabled: bool :param layout:", "been inherited from a parent layout. This is expected to", "'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'},", "of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the contribution.", "str :param projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param", "\"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field':", "_attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key':", "is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model):", "self.order = order self.overridden = overridden self.visible = visible class", "{'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata':", "'typeId', 'type': 'str'} } def __init__(self, description=None, name=None, projects=None, properties=None,", "class Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map", "is_contribution: bool :param label: Label for the field :type label:", ":type overridden: bool \"\"\" _attribute_map = { 'groups': {'key': 'groups',", "contribution are not. :type is_contribution: bool :param label: The label", "target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type = action_type self.target_field = target_field", "WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type behavior_field_id: str :param id: :type", "= description self.is_default = is_default self.is_enabled = is_enabled self.name =", "{'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states':", "visible: A value indicating if the page should be hidden", "'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} } def", "'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections',", "order self.state_category = state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior.", ":param is_disabled: :type is_disabled: bool :param is_system: :type is_system: bool", "{'key': 'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} }", "for the layout node. :type id: str :param overridden: A", "should appear in the layout. :type order: int :param overridden:", "{ 'color': {'key': 'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type':", "{'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} }", "page. :type label: str :param locked: A value indicating whether", "contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A value indicating", "{'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} }", "def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description =", "target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type", "'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url',", "properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str", "description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name", "'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible': {'key': 'visible',", "'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url',", "behavior and will be lost if the code is regenerated.", "is_default: bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type", "self.visible = visible class Page(Model): \"\"\"Page. :param contribution: Contribution for", "'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type':", "{'key': 'url', 'type': 'str'} } def __init__(self, color=None, hidden=None, id=None,", "layout. :type overridden: bool :param read_only: A value indicating if", "value indicating if the control should be hidden or not.", "self.description = description self.fields = fields self.id = id self.inherits", "'name', 'type': 'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key':", ":type description: str :param is_default: :type is_default: bool :param is_enabled:", "the page. :type page_type: object :param sections: The sections of", "id self.is_identity = is_identity self.name = name self.type = type", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url',", "overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description: str :param", "WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the contribution. :type", "is contribution are not. :type is_contribution: bool :param label: Label", "state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden = hidden", ":param locked: A value indicating whether any user operations are", "'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type':", "= page_type self.sections = sections self.visible = visible class ProcessModel(Model):", "is_enabled: :type is_enabled: bool :param name: :type name: str \"\"\"", "'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'},", "'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type':", ":type id: str :param inherited: A value indicating whether this", "class ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param id:", "'str'}, 'version': {'key': 'version', 'type': 'str'} } def __init__(self, class_=None,", "{'key': 'overridden', 'type': 'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections':", "'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key': 'locked',", "self.hidden = hidden self.id = id self.name = name self.order", "inherited self.is_contribution = is_contribution self.label = label self.metadata = metadata", "'value': {'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None,", "controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group,", "\"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'name':", "indicating if the layout node is contribution are not. :type", "= fields self.id = id self.inherits = inherits self.name =", "visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type':", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, behavior_field_id=None, id=None,", "= value class Section(Model): \"\"\"Section. :param groups: :type groups: list", "is_disabled self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets", "for the contribution. :type height: int :param id: The id", "'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}", "'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'} } def", "list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if", "description: str :param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>`", "is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The", "{'key': 'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None):", ":type parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\" _attribute_map", "'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} } def __init__(self,", "class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field:", "and sets extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>`", "{'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order':", "bool :param order: Order in which the page should appear", "inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control,", "'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'}, 'overridden': {'key':", "= condition_type self.field = field self.value = value class Section(Model):", "\"\"\"RuleConditionModel. :param condition_type: :type condition_type: str :param field: :type field:", "the group. :type label: str :param order: Order in which", "is contribution are not. :type is_contribution: bool :param label: The", "A value indicating whether any user operations are permitted on", "str :param fields: :type fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param", "_attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'id': {'key':", "= id self.name = name self.order = order self.state_category =", "id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url", "the project root for license information. # -------------------------------------------------------------------------------------------- # Generated", ":type is_system: bool \"\"\" _attribute_map = { 'actions': {'key': 'actions',", "The sections of the page. :type sections: list of :class:`Section", "height: int :param inputs: A dictionary holding key value pairs", "= order self.overridden = overridden self.read_only = read_only self.visible =", "\"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'controls':", "'name': {'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'},", "{'key': 'typeId', 'type': 'str'} } def __init__(self, description=None, name=None, projects=None,", ":param is_disabled: :type is_disabled: bool :param layout: :type layout: :class:`FormLayout", "id: :type id: str :param name: :type name: str :param", "self).__init__() self.behavior = behavior self.is_default = is_default self.url = url", "{ 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type':", "behavior self.is_default = is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel.", "'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None):", "'[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type':", ":param name: :type name: str :param parent_process_type_id: :type parent_process_type_id: str", ":param contribution: Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>`", "'str'} } def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id =", "<work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param id: :type id:", "'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version',", "bool :param rank: :type rank: int :param url: :type url:", "'[Extension]'}, 'pages': {'key': 'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type':", ":type url: str \"\"\" _attribute_map = { 'color': {'key': 'color',", "appear in the layout. :type order: int :param overridden: A", "watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type = control_type self.height", "'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'locked': {'key':", "'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type':", "<work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the layout. :type", ":type rank: int :param url: :type url: str \"\"\" _attribute_map", "contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None):", "{'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None, name=None,", "= inherits self.name = name self.overriden = overriden self.rank =", "str :param height: Height of the control, for html controls.", "'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type':", "= id self.inherits = inherits self.name = name self.overriden =", "class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param id:", "hidden: bool :param id: :type id: str :param name: :type", "self.name = name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param", "super(FieldModel, self).__init__() self.description = description self.id = id self.is_identity =", "id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type", ":param type: :type type: object :param url: :type url: str", "system_controls: Headers controls of the layout. :type system_controls: list of", "class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color:", "FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions list :type", "-------------------------------------------------------------------------------------------- from msrest.serialization import Model class Control(Model): \"\"\"Control. :param contribution:", ":type value: str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType',", "'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type': '[WorkItemBehaviorField]'},", "'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label',", "control, for html controls. :type height: int :param id: The", "id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color: :type", "{'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None,", "name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type':", "A value indicating if the page should be hidden or", "ReferenceName that it inherits from :type inherits: str :param is_disabled:", "description self.name = name self.projects = projects self.properties = properties", "= name self.projects = projects self.properties = properties self.reference_name =", "str :param id: :type id: str :param url: :type url:", "group should appear in the section. :type order: int :param", "\"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id':", "'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None,", "'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key': 'name',", "= class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id =", "self.color = color self.hidden = hidden self.id = id self.name", "_attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key':", "= locked self.order = order self.overridden = overridden self.page_type =", "int :param inputs: A dictionary holding key value pairs for", "'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId',", "fields: list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str", "of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the layout", "for the layout node. :type id: str :param inherited: A", "sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id = id", "order self.overridden = overridden self.page_type = page_type self.sections = sections", "pairs for contribution inputs. :type inputs: dict :param show_on_deleted_work_item: A", "'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type':", "set by the combiner. :type inherited: bool :param is_contribution: A", ":type condition_type: str :param field: :type field: str :param value:", "visible=None): super(Page, self).__init__() self.contribution = contribution self.id = id self.inherited", "'order': {'key': 'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'},", "super(CreateProcessModel, self).__init__() self.description = description self.name = name self.parent_process_type_id =", ":type field: str :param value: :type value: str \"\"\" _attribute_map", "'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } def", "'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key':", "group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The", "'type': 'str'} } def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None,", "show_on_deleted_work_item: A value indicating if the contribution should be show", "self).__init__() self.contribution_id = contribution_id self.height = height self.inputs = inputs", ":type description: str :param id: :type id: str :param is_identity:", "code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class", "'object'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None,", "\"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param color: :type color:", ":param visible: A value indicating if the control should be", "License. See License.txt in the project root for license information.", "{'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution':", "value: :type value: str \"\"\" _attribute_map = { 'condition_type': {'key':", "dictionary holding key value pairs for contribution inputs. :type inputs:", "{'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'} }", "{ 'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type':", ":param url: :type url: str \"\"\" _attribute_map = { 'behavior':", "projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name", "'description': {'key': 'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "'layout', 'type': 'FormLayout'}, 'name': {'key': 'name', 'type': 'str'}, 'states': {'key':", "__init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ =", ":type height: int :param inputs: A dictionary holding key value", "read_only self.visible = visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel.", "layout. :type order: int :param overridden: A value indicating whether", "self.id = id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param", "has been inherited from a parent layout. This is expected", "type_id=None): super(ProcessModel, self).__init__() self.description = description self.name = name self.projects", "def __init__(self, id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model):", "'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'}", "not. :type is_contribution: bool :param label: Label for the group.", "str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name:", "controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for", "'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type':", "NOT EDIT # Changes may cause incorrect behavior and will", "Type of the control. :type control_type: str :param height: Height", "is_disabled: bool :param is_system: :type is_system: bool \"\"\" _attribute_map =", ":class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the page", "overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution self.id", "= id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param color:", ":type name: str :param order: :type order: int :param state_category:", "= id self.name = name self.url = url class RuleActionModel(Model):", "def __init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None,", "self.projects = projects self.properties = properties self.reference_name = reference_name self.type_id", ":type name: str :param states: :type states: list of :class:`WorkItemStateResultModel", "self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description: :type", ":type label: str :param metadata: Inner text of the control.", "are not. :type is_contribution: bool :param label: Label for the", "__init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default", "'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key':", "if the control is readonly. :type read_only: bool :param visible:", "{'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'visible':", "'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str :param states:", "\"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_':", "'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self,", ":type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the control.", "{'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout':", "} def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None,", "'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key':", "'type': 'WitContribution'}, 'controls': {'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height',", "self.action_type = action_type self.target_field = target_field self.value = value class", "'type': 'str'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled',", "should appear in the section. :type order: int :param overridden:", "{'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited':", "'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key':", "= color self.description = description self.fields = fields self.id =", ":type id: str :param overridden: A value indicating whether this", "'inherited', 'type': 'bool'}, 'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key':", "extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs", "projects: :type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type", "child layout. :type overridden: bool :param read_only: A value indicating", "\"\"\" _attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'is_default':", "'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type':", "list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key':", "'[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None,", ":type show_on_deleted_work_item: bool \"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId',", ":type locked: bool :param order: Order in which the page", "\"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field: :type target_field:", "parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default = is_default", "{'key': 'name', 'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties':", "order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution", "= rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id:", "'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata',", "= { 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault',", "name=None): super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default self.is_enabled", "{'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order':", ":param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_:", "contribution should be show on deleted workItem. :type show_on_deleted_work_item: bool", "name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ =", "'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId',", "a child layout. :type overridden: bool :param read_only: A value", "'referenceName', 'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None):", "{'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type':", "self.id = id self.name = name self.url = url class", "'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'},", "= contribution self.id = id self.inherited = inherited self.is_contribution =", "conditions: :type conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type", "'type': 'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None,", "'str'} } def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None,", "'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'},", "<work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url: :type url:", "\"\"\"Page. :param contribution: Contribution for the page. :type contribution: :class:`WitContribution", "Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\" _attribute_map =", "child layout. :type overridden: bool :param page_type: The icon for", "color self.description = description self.fields = fields self.id = id", "self.icon = icon self.id = id self.inherits = inherits self.is_disabled", "is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions = conditions", "'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'projects': {'key':", ":type value: str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType',", "= { 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url',", "id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color", ":param name: :type name: str :param url: :type url: str", "name: str :param url: :type url: str \"\"\" _attribute_map =", "object :param is_default: :type is_default: bool :param is_enabled: :type is_enabled:", "'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key':", "super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel. :param description:", "\"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param", "str \"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'},", "node. :type id: str :param inherited: A value indicating whether", "= sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description:", "section. :type order: int :param overridden: A value indicating whether", "only be only set by the combiner. :type inherited: bool", "self.contribution_id = contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item", "'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name',", "'id', 'type': 'str'} } def __init__(self, id=None): super(Extension, self).__init__() self.id", "'type': 'str'} } def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference,", ":type id: str :param is_disabled: :type is_disabled: bool :param is_system:", "str :param name: :type name: str :param parent_process_type_id: :type parent_process_type_id:", "{'key': 'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id':", "'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key':", "'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key':", "= description self.id = id self.is_identity = is_identity self.name =", ":param overriden: :type overriden: bool :param rank: :type rank: int", "self.is_disabled = is_disabled self.layout = layout self.name = name self.states", "description: str :param icon: :type icon: str :param id: :type", "'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type':", "'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible',", "of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type conditions: list of :class:`RuleConditionModel", ":type label: str :param order: Order in which the group", "self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type:", "contribution self.controls = controls self.height = height self.id = id", ":type overridden: bool :param read_only: A value indicating if the", "'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self,", "'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel,", "'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type':", "def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__()", "group should be hidden or not. :type visible: bool \"\"\"", "description: str :param is_default: :type is_default: bool :param is_enabled: :type", "'[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None,", "only set by the combiner. :type inherited: bool :param is_contribution:", "the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model", "= color self.hidden = hidden self.id = id self.name =", "in which the group should appear in the section. :type", "= state_category self.url = url class WorkItemTypeBehavior(Model): \"\"\"WorkItemTypeBehavior. :param behavior:", "_attribute_map = { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key':", "'[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type':", "'id', 'type': 'str'}, 'inherited': {'key': 'inherited', 'type': 'bool'}, 'is_contribution': {'key':", "{ 'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type':", "on this page and the contents of this page :type", "is_default self.is_enabled = is_enabled self.name = name class WitContribution(Model): \"\"\"WitContribution.", "control_type: str :param height: Height of the control, for html", "'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_identity': {'key':", "the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id", ":param name: :type name: str :param overriden: :type overriden: bool", "show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool :param", "url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_ self.color", "str :param id: :type id: str :param inherits: Parent WIT", "is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets extensions", "under the MIT License. See License.txt in the project root", "read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type =", "bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'},", "super(WorkItemBehavior, self).__init__() self.abstract = abstract self.color = color self.description =", "order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution = contribution", "'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId',", "= friendly_name self.id = id self.is_disabled = is_disabled self.is_system =", "the page should be hidden or not. :type visible: bool", "__init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions", "} def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__() self.description", "= is_contribution self.label = label self.metadata = metadata self.order =", "self.id = id self.url = url class WorkItemStateResultModel(Model): \"\"\"WorkItemStateResultModel. :param", "{'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None,", "{ 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type':", "is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__()", "__init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description", "{ 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type':", "the control should be hidden or not. :type visible: bool", "'bool'} } def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None,", "str :param is_disabled: :type is_disabled: bool :param layout: :type layout:", "the contribution. :type height: int :param inputs: A dictionary holding", ":param class_: :type class_: object :param color: :type color: str", "url: :type url: str \"\"\" _attribute_map = { 'abstract': {'key':", "str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'},", "str :param name: :type name: str :param url: :type url:", "{'key': 'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible':", "'str'}, 'id': {'key': 'id', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type':", "super(ProjectReference, self).__init__() self.description = description self.id = id self.name =", "contribution: Contribution for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param", "'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark', 'type': 'str'}", "target_field: str :param value: :type value: str \"\"\" _attribute_map =", "'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel,", ":param is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str", "url=None): super(ProjectReference, self).__init__() self.description = description self.id = id self.name", "A value indicating if the contribution should be show on", "description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel,", "class_: :type class_: object :param color: :type color: str :param", "'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'} } def", ":type is_identity: bool :param name: :type name: str :param type:", "bool :param label: The label for the page. :type label:", "= description self.name = name self.projects = projects self.properties =", "name: :type name: str :param parent_process_type_id: :type parent_process_type_id: str :param", "'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self,", "actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions =", "name self.projects = projects self.properties = properties self.reference_name = reference_name", "contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height", "behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default =", "str :param target_field: :type target_field: str :param value: :type value:", ":type behavior_field_id: str :param id: :type id: str :param url:", "reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_: :type", "'version': {'key': 'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None,", "'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'},", ":param extensions: Gets and sets extensions list :type extensions: list", "= id self.inherited = inherited self.is_contribution = is_contribution self.label =", "'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description': {'key': 'description', 'type':", ":type control_type: str :param height: Height of the control, for", "is_identity: bool :param name: :type name: str :param type: :type", "\"\"\"Section. :param groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param", ":type reference_name: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "for the page. :type page_type: object :param sections: The sections", "self.groups = groups self.id = id self.overridden = overridden class", "'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem',", "'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'},", "bool :param page_type: The icon for the page. :type page_type:", ":param id: The id for the layout node. :type id:", "has been overridden by a child layout. :type overridden: bool", "'str'} } def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type", "name: :type name: str :param states: :type states: list of", "is_contribution: bool :param label: The label for the page. :type", ":param system_controls: Headers controls of the layout. :type system_controls: list", "self.height = height self.id = id self.inherited = inherited self.is_contribution", "layout node has been overridden by a child layout. :type", "self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param condition_type: :type condition_type:", "'overridden', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'} } def", "self.name = name self.projects = projects self.properties = properties self.reference_name", "url=None): super(FieldModel, self).__init__() self.description = description self.id = id self.is_identity", "description: :type description: str :param fields: :type fields: list of", "<work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map = {", "'type': 'str'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName',", "root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO", "class Page(Model): \"\"\"Page. :param contribution: Contribution for the page. :type", "name: :type name: str \"\"\" _attribute_map = { 'description': {'key':", "'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None): super(WorkItemTypeBehavior,", "{'key': 'id', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} }", "{'key': 'url', 'type': 'str'} } def __init__(self, behavior=None, is_default=None, url=None):", "by a child layout. :type overridden: bool :param page_type: The", ":type url: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "self.control_type = control_type self.height = height self.id = id self.inherited", "str :param is_identity: :type is_identity: bool :param name: :type name:", "'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key': 'order', 'type': 'int'},", "show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height self.inputs", "'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'},", "of the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\"", ":type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the", "{'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item':", "{'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'}, 'name':", "'color', 'type': 'str'}, 'hidden': {'key': 'hidden', 'type': 'bool'}, 'id': {'key':", "value indicating if the layout node is contribution or not.", "'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs',", "operations are permitted on this page and the contents of", "icon self.id = id self.inherits = inherits self.is_disabled = is_disabled", "value pairs for contribution inputs. :type inputs: dict :param show_on_deleted_work_item:", "rank: int :param url: :type url: str \"\"\" _attribute_map =", "'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon', 'type':", "The height for the contribution. :type height: int :param inputs:", "control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of the", "_attribute_map = { 'behavior': {'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key':", "behaviors self.class_ = class_ self.color = color self.description = description", "textbox. :type watermark: str \"\"\" _attribute_map = { 'contribution': {'key':", "= id self.is_disabled = is_disabled self.is_system = is_system class FormLayout(Model):", "page should be hidden or not. :type visible: bool \"\"\"", "height for the contribution. :type height: int :param inputs: A", "inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page,", "{'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url':", "node is contribution or not. :type is_contribution: bool :param label:", "__init__(self, abstract=None, color=None, description=None, fields=None, id=None, inherits=None, name=None, overriden=None, rank=None,", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type':", "__init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None,", "behaviors=None, class_=None, color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None,", "conditions: list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str", "{'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'id':", "self.is_contribution = is_contribution self.label = label self.metadata = metadata self.order", "name: str :param type: :type type: object :param url: :type", ":param page_type: The icon for the page. :type page_type: object", "self.color = color self.description = description self.icon = icon self.id", ":type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param", "'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None,", "text for the textbox. :type watermark: str \"\"\" _attribute_map =", "pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages = pages", "in the section. :type order: int :param overridden: A value", "_attribute_map = { 'abstract': {'key': 'abstract', 'type': 'bool'}, 'color': {'key':", "the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible:", "'url', 'type': 'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None,", "self.friendly_name = friendly_name self.id = id self.is_disabled = is_disabled self.is_system", "= controls self.height = height self.id = id self.inherited =", "layout. :type overridden: bool :param visible: A value indicating if", "'isSystem', 'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None,", "self.order = order self.overridden = overridden self.page_type = page_type self.sections", ":param visible: A value indicating if the page should be", "list of :class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param", "value class Section(Model): \"\"\"Section. :param groups: :type groups: list of", "url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param", "id self.inherits = inherits self.name = name self.overriden = overriden", "contribution self.control_type = control_type self.height = height self.id = id", "'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id',", "'description', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key':", ":type url: str \"\"\" _attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId',", "A value indicating if the control should be hidden or", "reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name = name", "'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def", "{'key': 'isEnabled', 'type': 'bool'}, 'parent_process_type_id': {'key': 'parentProcessTypeId', 'type': 'str'}, 'version':", "_attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key':", "= show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract: bool", "overridden: bool \"\"\" _attribute_map = { 'groups': {'key': 'groups', 'type':", "url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url", "A dictionary holding key value pairs for contribution inputs. :type", "state_category: :type state_category: str :param url: :type url: str \"\"\"", "'[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type':", "super(Group, self).__init__() self.contribution = contribution self.controls = controls self.height =", "'type': 'bool'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "= id self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id:", "self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions:", "_attribute_map = { 'description': {'key': 'description', 'type': 'str'}, 'is_default': {'key':", ":param inherits: Parent WIT Id/Internal ReferenceName that it inherits from", "pages self.system_controls = system_controls class Group(Model): \"\"\"Group. :param contribution: Contribution", "description self.fields = fields self.id = id self.inherits = inherits", "type=None, url=None): super(FieldModel, self).__init__() self.description = description self.id = id", "layout self.name = name self.states = states self.url = url", "} def __init__(self, contribution=None, control_type=None, height=None, id=None, inherited=None, is_contribution=None, label=None,", "rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param behavior_field_id: :type", "any user operations are permitted on this page and the", "'str'} } def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None,", "from :type inherits: str :param is_disabled: :type is_disabled: bool :param", "self.controls = controls self.height = height self.id = id self.inherited", ":param description: :type description: str :param fields: :type fields: list", "'pages', 'type': '[Page]'}, 'system_controls': {'key': 'systemControls', 'type': '[Control]'} } def", "list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>`", ":type class_: object :param is_default: :type is_default: bool :param is_enabled:", "abstract self.color = color self.description = description self.fields = fields", "'isEnabled', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'} } def", "id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions self.conditions =", ":param controls: Controls to be put in the group. :type", "A value indicating whether this layout node has been inherited", "'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'},", "contribution. :type height: int :param id: The id for the", "class_ self.is_default = is_default self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id", "Contribution for the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls:", "label: The label for the page. :type label: str :param", "controls self.height = height self.id = id self.inherited = inherited", "is_enabled: :type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param", ":type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_:", "\"\"\"Control. :param contribution: Contribution for the control. :type contribution: :class:`WitContribution", "overridden: bool :param visible: A value indicating if the group", "'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'},", "{'key': 'abstract', 'type': 'bool'}, 'color': {'key': 'color', 'type': 'str'}, 'description':", "'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type': 'str'}", "the layout node is contribution are not. :type is_contribution: bool", "} def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id =", "list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top", "{'key': 'fields', 'type': '[WorkItemBehaviorField]'}, 'id': {'key': 'id', 'type': 'str'}, 'inherits':", "self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension. :param", "str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}", "'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value', 'type':", "= id self.is_identity = is_identity self.name = name self.type =", "list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of the", "fields self.id = id self.inherits = inherits self.name = name", "= name self.type = type self.url = url class FieldRuleModel(Model):", "self.description = description self.icon = icon self.id = id self.inherits", ":type id: str :param url: :type url: str \"\"\" _attribute_map", "description: str :param id: :type id: str :param name: :type", "'bool'}, 'name': {'key': 'name', 'type': 'str'} } def __init__(self, description=None,", "'type': 'int'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited',", "_attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field': {'key':", ":param value: :type value: str \"\"\" _attribute_map = { 'condition_type':", "{'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} }", "overridden by a child layout. :type overridden: bool \"\"\" _attribute_map", ":type visible: bool \"\"\" _attribute_map = { 'contribution': {'key': 'contribution',", ":param name: :type name: str :param projects: :type projects: list", "'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem',", "{ 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages', 'type':", "{'key': 'version', 'type': 'str'} } def __init__(self, class_=None, is_default=None, is_enabled=None,", "'contribution', 'type': 'WitContribution'}, 'control_type': {'key': 'controlType', 'type': 'str'}, 'height': {'key':", "'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key':", ":param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name:", "'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key':", ":param id: :type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference", "is_identity: :type is_identity: bool :param name: :type name: str :param", "list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of", "'str'}, 'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type':", "self).__init__() self.contribution = contribution self.control_type = control_type self.height = height", "extensions list :type extensions: list of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages:", "are permitted on this page and the contents of this", "'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type': '[Section]'},", "'type': 'WorkItemBehaviorReference'}, 'name': {'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden',", "_attribute_map = { 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key':", "inherited from a parent layout. This is expected to only", "id: :type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>`", "self.target_field = target_field self.value = value class RuleConditionModel(Model): \"\"\"RuleConditionModel. :param", ":param height: The height for the contribution. :type height: int", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, description=None, id=None,", "id for the layout node. :type id: str :param overridden:", "inherits self.name = name self.overriden = overriden self.rank = rank", "= order self.overridden = overridden self.page_type = page_type self.sections =", "= { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height',", "incorrect behavior and will be lost if the code is", "{'key': 'behavior', 'type': 'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url':", "self).__init__() self.description = description self.id = id self.name = name", ":param watermark: Watermark text for the textbox. :type watermark: str", "in the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param", "list of :class:`Control <work-item-tracking.v4_0.models.Control>` :param height: The height for the", "'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'},", "color=None, description=None, icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None):", ":type is_default: bool :param is_enabled: :type is_enabled: bool :param parent_process_type_id:", "may cause incorrect behavior and will be lost if the", "= description self.icon = icon self.id = id self.inherits =", "properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type reference_name: str :param type_id:", "list of :class:`RuleConditionModel <work-item-tracking.v4_0.models.RuleConditionModel>` :param friendly_name: :type friendly_name: str :param", ":param order: :type order: int :param state_category: :type state_category: str", "'str'} } def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None):", "= read_only self.visible = visible self.watermark = watermark class CreateProcessModel(Model):", "'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'order': {'key':", "'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank', 'type': 'int'},", "'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name': {'key':", "= behaviors self.class_ = class_ self.color = color self.description =", "__init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url =", "inherited: A value indicating whether this layout node has been", "abstract: bool :param color: :type color: str :param description: :type", "'icon': {'key': 'icon', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key': 'typeId', 'type': 'str'}", "page :type locked: bool :param order: Order in which the", "'hidden', 'type': 'bool'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key':", ":type action_type: str :param target_field: :type target_field: str :param value:", "layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name: str", "'parentProcessTypeId', 'type': 'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def", "The id for the layout node. :type id: str :param", "label: str :param locked: A value indicating whether any user", "not. :type visible: bool :param watermark: Watermark text for the", "} def __init__(self, condition_type=None, field=None, value=None): super(RuleConditionModel, self).__init__() self.condition_type =", "'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type': 'str'}", "condition_type self.field = field self.value = value class Section(Model): \"\"\"Section.", "= height self.id = id self.inherited = inherited self.is_contribution =", "= watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type description: str", "\"\"\"CreateProcessModel. :param description: :type description: str :param name: :type name:", "color: str :param description: :type description: str :param icon: :type", "self.id = id self.is_identity = is_identity self.name = name self.type", "for the field :type label: str :param metadata: Inner text", "friendly_name: str :param id: :type id: str :param is_disabled: :type", "'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields',", "= name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model):", "whether this layout node has been overridden by a child", "{'key': 'id', 'type': 'str'}, 'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name':", "'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__()", "'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type':", "states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str", ":class:`WorkItemBehaviorField <work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits: :type", "'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden', 'type': 'bool'}", ":param contribution: Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>`", "self.description = description self.is_default = is_default self.is_enabled = is_enabled self.name", "layout. :type overridden: bool :param page_type: The icon for the", "be only set by the combiner. :type inherited: bool :param", "<work-item-tracking.v4_0.models.WorkItemBehaviorField>` :param id: :type id: str :param inherits: :type inherits:", "{'key': 'isDisabled', 'type': 'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} }", "value indicating if the contribution should be show on deleted", ":type color: str :param description: :type description: str :param icon:", "or not. :type is_contribution: bool :param label: Label for the", "id: str :param is_identity: :type is_identity: bool :param name: :type", "'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'icon': {'key': 'icon',", "'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'str'}, 'is_disabled': {'key':", "name self.parent_process_type_id = parent_process_type_id self.reference_name = reference_name class Extension(Model): \"\"\"Extension.", "} def __init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None,", "'str'} } def __init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id", "__init__(self, contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None,", ":class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name:", "url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default self.url", "WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>`", "a child layout. :type overridden: bool \"\"\" _attribute_map = {", "bool :param is_enabled: :type is_enabled: bool :param name: :type name:", "'inherits', 'type': 'str'}, 'is_disabled': {'key': 'isDisabled', 'type': 'bool'}, 'layout': {'key':", "= reference_name self.type_id = type_id class ProcessProperties(Model): \"\"\"ProcessProperties. :param class_:", "by a child layout. :type overridden: bool :param read_only: A", "fields=None, id=None, inherits=None, name=None, overriden=None, rank=None, url=None): super(WorkItemBehavior, self).__init__() self.abstract", "= { 'extensions': {'key': 'extensions', 'type': '[Extension]'}, 'pages': {'key': 'pages',", "= id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description:", "url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url class", "the combiner. :type inherited: bool :param is_contribution: A value indicating", "def __init__(self, contribution=None, controls=None, height=None, id=None, inherited=None, is_contribution=None, label=None, order=None,", "actions: :type actions: list of :class:`RuleActionModel <work-item-tracking.v4_0.models.RuleActionModel>` :param conditions: :type", ":param name: :type name: str :param states: :type states: list", "\"\"\" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'url':", "id class FieldModel(Model): \"\"\"FieldModel. :param description: :type description: str :param", "{'key': 'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value':", "tabs of the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>`", "'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'}, 'value': {'key': 'value',", "label self.locked = locked self.order = order self.overridden = overridden", "{'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name':", "'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'url': {'key': 'url',", "if the page should be hidden or not. :type visible:", "{'key': 'value', 'type': 'str'} } def __init__(self, action_type=None, target_field=None, value=None):", ":type id: str :param inherits: :type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param", "description: :type description: str :param name: :type name: str :param", "be hidden or not. :type visible: bool :param watermark: Watermark", "the MIT License. See License.txt in the project root for", "of :class:`Extension <work-item-tracking.v4_0.models.Extension>` :param pages: Top level tabs of the", "or not. :type visible: bool :param watermark: Watermark text for", "__init__(self, behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id", "url: :type url: str \"\"\" _attribute_map = { 'behavior': {'key':", "'{object}'}, 'show_on_deleted_work_item': {'key': 'showOnDeletedWorkItem', 'type': 'bool'} } def __init__(self, contribution_id=None,", "} def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel, self).__init__() self.description", "field: :type field: str :param value: :type value: str \"\"\"", "'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key': 'order', 'type':", ":param sections: The sections of the page. :type sections: list", ":type type_id: str \"\"\" _attribute_map = { 'description': {'key': 'description',", "'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key':", "self.is_contribution = is_contribution self.label = label self.order = order self.overridden", ":type id: str \"\"\" _attribute_map = { 'id': {'key': 'id',", "str :param type: :type type: object :param url: :type url:", ":param name: :type name: str \"\"\" _attribute_map = { 'description':", "the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param control_type: Type of", "url: str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type':", "= is_disabled self.layout = layout self.name = name self.states =", "import Model class Control(Model): \"\"\"Control. :param contribution: Contribution for the", "'isDisabled', 'type': 'bool'}, 'layout': {'key': 'layout', 'type': 'FormLayout'}, 'name': {'key':", "= is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and sets", "= is_contribution self.label = label self.locked = locked self.order =", "layout node. :type id: str :param inherited: A value indicating", ":param reference_name: :type reference_name: str \"\"\" _attribute_map = { 'description':", ":param pages: Top level tabs of the layout. :type pages:", "'str'}, 'reference_name': {'key': 'referenceName', 'type': 'str'} } def __init__(self, description=None,", "= is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors:", "{'key': 'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type':", "is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default =", "bool :param name: :type name: str \"\"\" _attribute_map = {", "color: :type color: str :param hidden: :type hidden: bool :param", ":type is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param", "Inner text of the control. :type metadata: str :param order:", "'systemControls', 'type': '[Control]'} } def __init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout,", "the group should appear in the section. :type order: int", "height=None, id=None, inherited=None, is_contribution=None, label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None,", "self.contribution = contribution self.control_type = control_type self.height = height self.id", "'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key': 'watermark',", "color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color", ":param is_default: :type is_default: bool :param is_enabled: :type is_enabled: bool", "{'key': 'stateCategory', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} }", "locked self.order = order self.overridden = overridden self.page_type = page_type", "'bool'}, 'rank': {'key': 'rank', 'type': 'int'}, 'url': {'key': 'url', 'type':", ":type is_enabled: bool :param parent_process_type_id: :type parent_process_type_id: str :param version:", "self).__init__() self.behavior_field_id = behavior_field_id self.id = id self.url = url", ":type color: str :param description: :type description: str :param fields:", ":type order: int :param state_category: :type state_category: str :param url:", "= name self.overriden = overriden self.rank = rank self.url =", "'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key':", "# Licensed under the MIT License. See License.txt in the", "contribution_id self.height = height self.inputs = inputs self.show_on_deleted_work_item = show_on_deleted_work_item", "rank: :type rank: int :param url: :type url: str \"\"\"", "def __init__(self, contribution_id=None, height=None, inputs=None, show_on_deleted_work_item=None): super(WitContribution, self).__init__() self.contribution_id =", "'order', 'type': 'int'}, 'state_category': {'key': 'stateCategory', 'type': 'str'}, 'url': {'key':", "metadata self.order = order self.overridden = overridden self.read_only = read_only", "'label': {'key': 'label', 'type': 'str'}, 'order': {'key': 'order', 'type': 'int'},", "str :param name: :type name: str :param order: :type order:", "self.show_on_deleted_work_item = show_on_deleted_work_item class WorkItemBehavior(Model): \"\"\"WorkItemBehavior. :param abstract: :type abstract:", "{'key': 'name', 'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank':", "= description self.id = id self.name = name self.url =", "properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description = description self.name =", "class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id: str :param url:", "bool :param label: Label for the field :type label: str", ":type label: str :param locked: A value indicating whether any", ":param url: :type url: str \"\"\" _attribute_map = { 'behaviors':", "{'key': 'description', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'parent_process_type_id':", "the group. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to", "class WitContribution(Model): \"\"\"WitContribution. :param contribution_id: The id for the contribution.", ":param overridden: A value indicating whether this layout node has", "{'key': 'url', 'type': 'str'} } def __init__(self, abstract=None, color=None, description=None,", "contribution: Contribution for the control. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param", "read_only: A value indicating if the control is readonly. :type", "of the layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param", "for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT", "name: str :param overriden: :type overriden: bool :param rank: :type", "\"\"\"Group. :param contribution: Contribution for the group. :type contribution: :class:`WitContribution", "super(UpdateProcessModel, self).__init__() self.description = description self.is_default = is_default self.is_enabled =", "'name', 'type': 'str'} } def __init__(self, description=None, is_default=None, is_enabled=None, name=None):", ":param id: :type id: str :param is_identity: :type is_identity: bool", "self).__init__() self.description = description self.id = id self.is_identity = is_identity", "id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id = id", "object :param sections: The sections of the page. :type sections:", "label=None, metadata=None, order=None, overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution", "cause incorrect behavior and will be lost if the code", "parent_process_type_id: :type parent_process_type_id: str :param version: :type version: str \"\"\"", "(c) Microsoft Corporation. All rights reserved. # Licensed under the", "url: :type url: str \"\"\" _attribute_map = { 'description': {'key':", "__init__(self, id=None): super(Extension, self).__init__() self.id = id class FieldModel(Model): \"\"\"FieldModel.", "self.id = id self.is_disabled = is_disabled self.is_system = is_system class", "readonly. :type read_only: bool :param visible: A value indicating if", ":param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type reference_name: str", "'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName', 'type': 'str'}, 'type_id': {'key':", "} def __init__(self, description=None, is_default=None, is_enabled=None, name=None): super(UpdateProcessModel, self).__init__() self.description", "= url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, color=None, hidden=None,", "'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'}, 'show_on_deleted_work_item': {'key':", "is_disabled: :type is_disabled: bool :param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>`", "\"\"\"WitContribution. :param contribution_id: The id for the contribution. :type contribution_id:", "'parentProcessTypeId', 'type': 'str'}, 'version': {'key': 'version', 'type': 'str'} } def", ":type type: object :param url: :type url: str \"\"\" _attribute_map", "'label', 'type': 'str'}, 'locked': {'key': 'locked', 'type': 'bool'}, 'order': {'key':", "the page. :type label: str :param locked: A value indicating", "super(WitContribution, self).__init__() self.contribution_id = contribution_id self.height = height self.inputs =", "order: Order in which the page should appear in the", "page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param visible: A", "'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'}", "{ 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key': 'id', 'type':", "self.is_system = is_system class FormLayout(Model): \"\"\"FormLayout. :param extensions: Gets and", "url: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "\"\"\" _attribute_map = { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions':", "'order', 'type': 'int'}, 'overridden': {'key': 'overridden', 'type': 'bool'}, 'page_type': {'key':", ":class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id for the layout node.", "= inherits self.is_disabled = is_disabled self.layout = layout self.name =", ":param is_default: :type is_default: bool :param url: :type url: str", "self.field = field self.value = value class Section(Model): \"\"\"Section. :param", "self).__init__() self.description = description self.is_default = is_default self.is_enabled = is_enabled", "= { 'actions': {'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions',", "name: str :param states: :type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>`", "is_contribution self.label = label self.metadata = metadata self.order = order", ":param condition_type: :type condition_type: str :param field: :type field: str", "sections of the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>`", "'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key':", "hidden or not. :type visible: bool \"\"\" _attribute_map = {", "'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key': 'overridden',", "_attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height': {'key':", "_attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'url': {'key':", "visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param description: :type", "'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, controls=None,", "'url', 'type': 'str'} } def __init__(self, description=None, id=None, name=None, url=None):", "action_type: str :param target_field: :type target_field: str :param value: :type", "'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order': {'key':", ":param is_identity: :type is_identity: bool :param name: :type name: str", ":type reference_name: str :param type_id: :type type_id: str \"\"\" _attribute_map", "{ 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type':", "is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_ = class_ self.is_default", "__init__(self, extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages", ":type watermark: str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution',", "'height': {'key': 'height', 'type': 'int'}, 'inputs': {'key': 'inputs', 'type': '{object}'},", "self.abstract = abstract self.color = color self.description = description self.fields", "= reference_name class Extension(Model): \"\"\"Extension. :param id: :type id: str", "'conditionType', 'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key':", "{'key': 'contributionId', 'type': 'str'}, 'height': {'key': 'height', 'type': 'int'}, 'inputs':", "groups=None, id=None, overridden=None): super(Section, self).__init__() self.groups = groups self.id =", ":param visible: A value indicating if the group should be", "str :param inherits: Parent WIT Id/Internal ReferenceName that it inherits", "self.inherited = inherited self.is_contribution = is_contribution self.label = label self.metadata", "contribution_id: The id for the contribution. :type contribution_id: str :param", "{'key': 'actions', 'type': '[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name':", "= url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param behaviors: :type behaviors: list", ":type name: str :param projects: :type projects: list of :class:`ProjectReference", "str \"\"\" _attribute_map = { 'action_type': {'key': 'actionType', 'type': 'str'},", "field: str :param value: :type value: str \"\"\" _attribute_map =", "'id': {'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'},", ":param url: :type url: str \"\"\" _attribute_map = { 'color':", "overridden self.read_only = read_only self.visible = visible self.watermark = watermark", "overriden self.rank = rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField.", "extensions: Gets and sets extensions list :type extensions: list of", "_attribute_map = { 'groups': {'key': 'groups', 'type': '[Group]'}, 'id': {'key':", "self.id = id self.inherits = inherits self.is_disabled = is_disabled self.layout", "condition_type: :type condition_type: str :param field: :type field: str :param", "sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param description: :type", "of the control. :type metadata: str :param order: :type order:", "self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type description:", "def __init__(self, description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__()", "bool :param visible: A value indicating if the control should", "} def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__()", "by a child layout. :type overridden: bool \"\"\" _attribute_map =", "overriden: :type overriden: bool :param rank: :type rank: int :param", "reference_name=None): super(CreateProcessModel, self).__init__() self.description = description self.name = name self.parent_process_type_id", ":type overriden: bool :param rank: :type rank: int :param url:", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "field :type label: str :param metadata: Inner text of the", "from a parent layout. This is expected to only be", "reference_name: str :param type_id: :type type_id: str \"\"\" _attribute_map =", "not. :type is_contribution: bool :param label: The label for the", "\"\"\" _attribute_map = { 'condition_type': {'key': 'conditionType', 'type': 'str'}, 'field':", "abstract: :type abstract: bool :param color: :type color: str :param", "class_ self.color = color self.description = description self.icon = icon", "layout. :type pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers", "'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type':", "\"\"\" _attribute_map = { 'contribution_id': {'key': 'contributionId', 'type': 'str'}, 'height':", ":param height: Height of the control, for html controls. :type", "behavior_field_id=None, id=None, url=None): super(WorkItemBehaviorField, self).__init__() self.behavior_field_id = behavior_field_id self.id =", "key value pairs for contribution inputs. :type inputs: dict :param", "'str'}, 'name': {'key': 'name', 'type': 'str'}, 'order': {'key': 'order', 'type':", "ProjectReference(Model): \"\"\"ProjectReference. :param description: :type description: str :param id: :type", "'str'}, 'states': {'key': 'states', 'type': '[WorkItemStateResultModel]'}, 'url': {'key': 'url', 'type':", "self.label = label self.locked = locked self.order = order self.overridden", "url: :type url: str \"\"\" _attribute_map = { 'color': {'key':", "'type': '[ProjectReference]'}, 'properties': {'key': 'properties', 'type': 'ProcessProperties'}, 'reference_name': {'key': 'referenceName',", "states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_ = class_", "behavior_field_id: str :param id: :type id: str :param url: :type", "'int'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self, abstract=None,", "'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'},", "'type': 'str'} } def __init__(self, description=None, name=None, parent_process_type_id=None, reference_name=None): super(CreateProcessModel,", "Corporation. All rights reserved. # Licensed under the MIT License.", ":type parent_process_type_id: str :param version: :type version: str \"\"\" _attribute_map", "controls: Controls to be put in the group. :type controls:", "behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type is_default: bool :param url:", ":class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param controls: Controls to be put in the", "self.behavior_field_id = behavior_field_id self.id = id self.url = url class", "order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__() self.color = color self.hidden =", "self.name = name self.type = type self.url = url class", "of the control. :type control_type: str :param height: Height of", "is_default: bool :param url: :type url: str \"\"\" _attribute_map =", ":type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = {", "self.is_enabled = is_enabled self.parent_process_type_id = parent_process_type_id self.version = version class", "behaviors: :type behaviors: list of :class:`WorkItemTypeBehavior <work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type", "'[WorkItemTypeBehavior]'}, 'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type':", "super(WorkItemBehaviorReference, self).__init__() self.id = id self.url = url class WorkItemStateResultModel(Model):", "inherits self.is_disabled = is_disabled self.layout = layout self.name = name", "of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param", "'type': 'bool'} } def __init__(self, actions=None, conditions=None, friendly_name=None, id=None, is_disabled=None,", "{ 'class_': {'key': 'class', 'type': 'object'}, 'is_default': {'key': 'isDefault', 'type':", "{'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id':", "be put in the group. :type controls: list of :class:`Control", "'groups', 'type': '[Group]'}, 'id': {'key': 'id', 'type': 'str'}, 'overridden': {'key':", "description self.icon = icon self.id = id self.inherits = inherits", "'str'}, 'description': {'key': 'description', 'type': 'str'}, 'fields': {'key': 'fields', 'type':", "contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The id for the layout", "field self.value = value class Section(Model): \"\"\"Section. :param groups: :type", "self.is_default = is_default self.is_enabled = is_enabled self.name = name class", "name: str :param parent_process_type_id: :type parent_process_type_id: str :param reference_name: :type", "'action_type': {'key': 'actionType', 'type': 'str'}, 'target_field': {'key': 'targetField', 'type': 'str'},", ":param url: :type url: str \"\"\" _attribute_map = { 'abstract':", "pages: list of :class:`Page <work-item-tracking.v4_0.models.Page>` :param system_controls: Headers controls of", "layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors self.class_", "str :param icon: :type icon: str :param id: :type id:", "{'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url':", "'url', 'type': 'str'} } def __init__(self, color=None, hidden=None, id=None, name=None,", "'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type': 'str'}, 'id': {'key': 'id',", "a parent layout. This is expected to only be only", "control is readonly. :type read_only: bool :param visible: A value", "name self.type = type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel.", "{'key': 'field', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'} }", "self.order = order self.state_category = state_category self.url = url class", "bool :param name: :type name: str :param type: :type type:", "'is_identity': {'key': 'isIdentity', 'type': 'bool'}, 'name': {'key': 'name', 'type': 'str'},", "the layout. :type system_controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map", "'is_default': {'key': 'isDefault', 'type': 'bool'}, 'is_enabled': {'key': 'isEnabled', 'type': 'bool'},", "by the combiner. :type inherited: bool :param is_contribution: A value", ":param id: :type id: str :param name: :type name: str", "class_: object :param color: :type color: str :param description: :type", "'str'} } def __init__(self, description=None, id=None, name=None, url=None): super(ProjectReference, self).__init__()", "reference_name: str \"\"\" _attribute_map = { 'description': {'key': 'description', 'type':", "'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None,", ":param hidden: :type hidden: bool :param id: :type id: str", "self.label = label self.order = order self.overridden = overridden self.visible", "'bool'}, 'label': {'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type':", "_attribute_map = { 'behavior_field_id': {'key': 'behaviorFieldId', 'type': 'str'}, 'id': {'key':", "self.url = url class WorkItemBehaviorReference(Model): \"\"\"WorkItemBehaviorReference. :param id: :type id:", ":param abstract: :type abstract: bool :param color: :type color: str", "the group should be hidden or not. :type visible: bool", "= name self.url = url class RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type:", "Group(Model): \"\"\"Group. :param contribution: Contribution for the group. :type contribution:", "hidden or not. :type visible: bool :param watermark: Watermark text", "<work-item-tracking.v4_0.models.Section>` :param visible: A value indicating if the page should", "__init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None): super(WorkItemStateResultModel, self).__init__()", "'type': 'str'}, 'projects': {'key': 'projects', 'type': '[ProjectReference]'}, 'properties': {'key': 'properties',", "type self.url = url class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type", "reference_name class Extension(Model): \"\"\"Extension. :param id: :type id: str \"\"\"", "_attribute_map = { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'control_type': {'key':", "actions self.conditions = conditions self.friendly_name = friendly_name self.id = id", "page_type self.sections = sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel.", "child layout. :type overridden: bool \"\"\" _attribute_map = { 'groups':", "type: object :param url: :type url: str \"\"\" _attribute_map =", "} def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel,", "def __init__(self, class_=None, is_default=None, is_enabled=None, parent_process_type_id=None, version=None): super(ProcessProperties, self).__init__() self.class_", "watermark: str \"\"\" _attribute_map = { 'contribution': {'key': 'contribution', 'type':", "self).__init__() self.class_ = class_ self.is_default = is_default self.is_enabled = is_enabled", "page_type: The icon for the page. :type page_type: object :param", "conditions=None, friendly_name=None, id=None, is_disabled=None, is_system=None): super(FieldRuleModel, self).__init__() self.actions = actions", "'visible': {'key': 'visible', 'type': 'bool'} } def __init__(self, contribution=None, id=None,", "'type': 'str'}, 'overriden': {'key': 'overriden', 'type': 'bool'}, 'rank': {'key': 'rank',", "url: str \"\"\" _attribute_map = { 'id': {'key': 'id', 'type':", "= name self.order = order self.state_category = state_category self.url =", "self.color = color self.description = description self.fields = fields self.id", "= description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name =", "put in the group. :type controls: list of :class:`Control <work-item-tracking.v4_0.models.Control>`", "'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'object'},", "class FieldRuleModel(Model): \"\"\"FieldRuleModel. :param actions: :type actions: list of :class:`RuleActionModel", "or not. :type visible: bool \"\"\" _attribute_map = { 'contribution':", "is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__() self.behaviors = behaviors", "'url': {'key': 'url', 'type': 'str'} } def __init__(self, behaviors=None, class_=None,", "id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel. :param description: :type", "self.visible = visible self.watermark = watermark class CreateProcessModel(Model): \"\"\"CreateProcessModel. :param", "of the page. :type sections: list of :class:`Section <work-item-tracking.v4_0.models.Section>` :param", ":type state_category: str :param url: :type url: str \"\"\" _attribute_map", "} def __init__(self, id=None, url=None): super(WorkItemBehaviorReference, self).__init__() self.id = id", "id: str :param name: :type name: str :param order: :type", "= inherited self.is_contribution = is_contribution self.label = label self.locked =", "= { 'contribution': {'key': 'contribution', 'type': 'WitContribution'}, 'id': {'key': 'id',", "'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def", "this layout node has been inherited from a parent layout.", "self.rank = rank self.url = url class WorkItemBehaviorField(Model): \"\"\"WorkItemBehaviorField. :param", "'controls', 'type': '[Control]'}, 'height': {'key': 'height', 'type': 'int'}, 'id': {'key':", ":type inherits: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param", ":param icon: :type icon: str :param id: :type id: str", "is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__()", "self.sections = sections self.visible = visible class ProcessModel(Model): \"\"\"ProcessModel. :param", "'str'}, 'type': {'key': 'type', 'type': 'object'}, 'url': {'key': 'url', 'type':", "label: Label for the field :type label: str :param metadata:", "icon=None, id=None, inherits=None, is_disabled=None, layout=None, name=None, states=None, url=None): super(WorkItemTypeModel, self).__init__()", ":type url: str \"\"\" _attribute_map = { 'behavior': {'key': 'behavior',", "'overridden', 'type': 'bool'}, 'read_only': {'key': 'readOnly', 'type': 'bool'}, 'visible': {'key':", "description self.is_default = is_default self.is_enabled = is_enabled self.name = name", "'readOnly', 'type': 'bool'}, 'visible': {'key': 'visible', 'type': 'bool'}, 'watermark': {'key':", "'url', 'type': 'str'} } def __init__(self, abstract=None, color=None, description=None, fields=None,", ":type states: list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url:", "\"\"\"WorkItemStateResultModel. :param color: :type color: str :param hidden: :type hidden:", "str \"\"\" _attribute_map = { 'class_': {'key': 'class', 'type': 'object'},", "str :param is_disabled: :type is_disabled: bool :param is_system: :type is_system:", ":param label: Label for the group. :type label: str :param", "self.is_default = is_default self.url = url class WorkItemTypeModel(Model): \"\"\"WorkItemTypeModel. :param", "list of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\"", "inherited=None, is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution =", "str :param overridden: A value indicating whether this layout node", "'type': 'str'}, 'field': {'key': 'field', 'type': 'str'}, 'value': {'key': 'value',", ":type name: str :param type: :type type: object :param url:", "self.behavior = behavior self.is_default = is_default self.url = url class", "label=None, locked=None, order=None, overridden=None, page_type=None, sections=None, visible=None): super(Page, self).__init__() self.contribution", "# Generated file, DO NOT EDIT # Changes may cause", "groups: :type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The", "'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'} } def", "is_contribution=None, label=None, order=None, overridden=None, visible=None): super(Group, self).__init__() self.contribution = contribution", "groups self.id = id self.overridden = overridden class UpdateProcessModel(Model): \"\"\"UpdateProcessModel.", "contribution=None, id=None, inherited=None, is_contribution=None, label=None, locked=None, order=None, overridden=None, page_type=None, sections=None,", "<work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties: :class:`ProcessProperties <work-item-tracking.v4_0.models.ProcessProperties>` :param reference_name: :type", "description self.id = id self.name = name self.url = url", "and will be lost if the code is regenerated. #", ":param order: :type order: int :param overridden: A value indicating", "overridden=None, read_only=None, visible=None, watermark=None): super(Control, self).__init__() self.contribution = contribution self.control_type", "of :class:`Control <work-item-tracking.v4_0.models.Control>` \"\"\" _attribute_map = { 'extensions': {'key': 'extensions',", "<work-item-tracking.v4_0.models.WorkItemTypeBehavior>` :param class_: :type class_: object :param color: :type color:", "Controls to be put in the group. :type controls: list", "id=None, is_identity=None, name=None, type=None, url=None): super(FieldModel, self).__init__() self.description = description", "self.is_identity = is_identity self.name = name self.type = type self.url", "visible class Page(Model): \"\"\"Page. :param contribution: Contribution for the page.", "'bool'}, 'is_system': {'key': 'isSystem', 'type': 'bool'} } def __init__(self, actions=None,", "reserved. # Licensed under the MIT License. See License.txt in", "self.extensions = extensions self.pages = pages self.system_controls = system_controls class", "self.overridden = overridden self.read_only = read_only self.visible = visible self.watermark", "id for the contribution. :type contribution_id: str :param height: The", "'type': 'WitContribution'}, 'id': {'key': 'id', 'type': 'str'}, 'inherited': {'key': 'inherited',", "} def __init__(self, color=None, hidden=None, id=None, name=None, order=None, state_category=None, url=None):", "the layout node. :type id: str :param overridden: A value", "is_contribution self.label = label self.locked = locked self.order = order", ":param layout: :type layout: :class:`FormLayout <work-item-tracking.v4_0.models.FormLayout>` :param name: :type name:", "contents of this page :type locked: bool :param order: Order", "'[RuleActionModel]'}, 'conditions': {'key': 'conditions', 'type': '[RuleConditionModel]'}, 'friendly_name': {'key': 'friendlyName', 'type':", "str \"\"\" _attribute_map = { 'behaviors': {'key': 'behaviors', 'type': '[WorkItemTypeBehavior]'},", "'bool'}, 'page_type': {'key': 'pageType', 'type': 'object'}, 'sections': {'key': 'sections', 'type':", "A value indicating if the layout node is contribution are", "text of the control. :type metadata: str :param order: :type", "parent_process_type_id: str :param reference_name: :type reference_name: str \"\"\" _attribute_map =", "{'key': 'label', 'type': 'str'}, 'metadata': {'key': 'metadata', 'type': 'str'}, 'order':", "A value indicating if the group should be hidden or", ":param show_on_deleted_work_item: A value indicating if the contribution should be", "'WorkItemBehaviorReference'}, 'is_default': {'key': 'isDefault', 'type': 'bool'}, 'url': {'key': 'url', 'type':", "{'key': 'id', 'type': 'str'}, 'inherits': {'key': 'inherits', 'type': 'WorkItemBehaviorReference'}, 'name':", "= metadata self.order = order self.overridden = overridden self.read_only =", ":type projects: list of :class:`ProjectReference <work-item-tracking.v4_0.models.ProjectReference>` :param properties: :type properties:", "A value indicating if the control is readonly. :type read_only:", "description: str :param id: :type id: str :param is_identity: :type", "layout node is contribution or not. :type is_contribution: bool :param", "control. :type metadata: str :param order: :type order: int :param", "is expected to only be only set by the combiner.", "label: Label for the group. :type label: str :param order:", "this page and the contents of this page :type locked:", "id self.inherited = inherited self.is_contribution = is_contribution self.label = label", "visible: A value indicating if the control should be hidden", ":class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param name: :type name: str :param overriden: :type", ":param url: :type url: str \"\"\" _attribute_map = { 'behavior_field_id':", "{'key': 'value', 'type': 'str'} } def __init__(self, condition_type=None, field=None, value=None):", "\"\"\"UpdateProcessModel. :param description: :type description: str :param is_default: :type is_default:", "for the page. :type contribution: :class:`WitContribution <work-item-tracking.v4_0.models.WitContribution>` :param id: The", "name=None, url=None): super(ProjectReference, self).__init__() self.description = description self.id = id", "description=None, name=None, projects=None, properties=None, reference_name=None, type_id=None): super(ProcessModel, self).__init__() self.description =", "extensions=None, pages=None, system_controls=None): super(FormLayout, self).__init__() self.extensions = extensions self.pages =", "'str'} } def __init__(self, description=None, id=None, is_identity=None, name=None, type=None, url=None):", "self).__init__() self.action_type = action_type self.target_field = target_field self.value = value", "self.description = description self.name = name self.parent_process_type_id = parent_process_type_id self.reference_name", ":type class_: object :param color: :type color: str :param description:", "'sections': {'key': 'sections', 'type': '[Section]'}, 'visible': {'key': 'visible', 'type': 'bool'}", "\"\"\"WorkItemTypeBehavior. :param behavior: :type behavior: :class:`WorkItemBehaviorReference <work-item-tracking.v4_0.models.WorkItemBehaviorReference>` :param is_default: :type", "= properties self.reference_name = reference_name self.type_id = type_id class ProcessProperties(Model):", "'class_': {'key': 'class', 'type': 'object'}, 'color': {'key': 'color', 'type': 'str'},", "bool :param watermark: Watermark text for the textbox. :type watermark:", ":type page_type: object :param sections: The sections of the page.", "rights reserved. # Licensed under the MIT License. See License.txt", "of :class:`WorkItemStateResultModel <work-item-tracking.v4_0.models.WorkItemStateResultModel>` :param url: :type url: str \"\"\" _attribute_map", "show on deleted workItem. :type show_on_deleted_work_item: bool \"\"\" _attribute_map =", "'is_contribution': {'key': 'isContribution', 'type': 'bool'}, 'label': {'key': 'label', 'type': 'str'},", "description: str :param name: :type name: str :param parent_process_type_id: :type", "RuleActionModel(Model): \"\"\"RuleActionModel. :param action_type: :type action_type: str :param target_field: :type", "'str'} } def __init__(self, behaviors=None, class_=None, color=None, description=None, icon=None, id=None,", ":type groups: list of :class:`Group <work-item-tracking.v4_0.models.Group>` :param id: The id", "is_default=None, url=None): super(WorkItemTypeBehavior, self).__init__() self.behavior = behavior self.is_default = is_default", "'type': 'str'}, 'url': {'key': 'url', 'type': 'str'} } def __init__(self,", "'height': {'key': 'height', 'type': 'int'}, 'id': {'key': 'id', 'type': 'str'},", "} def __init__(self, action_type=None, target_field=None, value=None): super(RuleActionModel, self).__init__() self.action_type =", "str :param metadata: Inner text of the control. :type metadata:", "str :param order: :type order: int :param overridden: A value" ]
[ "'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response def", "ids): \"\"\" hydrate relevant ids with data \"\"\" return class", "DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for", "'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key, value in", "executed \"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS if", "in obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year']", "pipeline that must be executed \"\"\" if fields is None:", "movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if", "'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj:", "def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids with", "redis pipeline that must be executed \"\"\" if fields is", "dict(zip(fields, values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if", "for idx in movies)) response = [] for movie in", "def fetch(self, ids): \"\"\" hydrate relevant ids with data \"\"\"", "abc from utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta", "LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__()", "values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres'", "setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates", "must be executed \"\"\" if fields is None: fields =", "utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def", "= [] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields)", "fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids with metadata,", "in obj: obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self,", "value in kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None,", "in kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False):", "value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class ids", "import abc from utils import LogMixin class Reponse(object): __metaclass__ =", "class ids with metadata, return redis pipeline that must be", "connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant", "from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response =", "movies, fields=None, from_index=False): \"\"\" hydrates class ids with metadata, return", "return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for m in", "\"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS if from_index:", "= int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m)", "\"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres']", "def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self,", "fields is None: fields = Movies.DEFAULT_FIELDS if from_index: movies =", "if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year' in", "ids with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS =", "metadata, return redis pipeline that must be executed \"\"\" if", "with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title',", "response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for m", "hydrate relevant ids with data \"\"\" return class Movies(Reponse, LogMixin):", "= ['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key,", "= Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in", "**kwargs): super().__init__() for key, value in kwargs.items(): setattr(self, key, value)", "relevant ids with data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS", "= self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for", "obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year'])", "in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values))", "in movies)) response = [] for movie in movies: values", "response = [] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie),", "\"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids", "self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = [] for movie", "redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids):", "= self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres' in", "response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for m in movies))", "from utils import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod", "be executed \"\"\" if fields is None: fields = Movies.DEFAULT_FIELDS", "LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\"", "'genres'] def __init__(self, **kwargs): super().__init__() for key, value in kwargs.items():", "class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis", "movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response = []", "fetch(self, ids): \"\"\" hydrate relevant ids with data \"\"\" return", "movies)) response = [] for movie in movies: values =", "if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return response", "['title', 'year', 'genres'] def __init__(self, **kwargs): super().__init__() for key, value", "None: fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for", "class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self,", "self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields, values)) if 'genres' in obj:", "\"\"\" hydrates class ids with metadata, return redis pipeline that", "= dict(zip(fields, values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',')", "return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids with", "def __init__(self, **kwargs): super().__init__() for key, value in kwargs.items(): setattr(self,", "key, value in kwargs.items(): setattr(self, key, value) def fetch(self, movies,", "int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return self.redis.mget(('index:movie:{}'.format(m) for", "data \"\"\" return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year',", "obj: obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self, movies):", "obj: obj['genres'] = obj['genres'].split(',') if 'year' in obj: obj['year'] =", "<reponame>ziggyzacks/pyrecs import abc from utils import LogMixin class Reponse(object): __metaclass__", "fields=None, from_index=False): \"\"\" hydrates class ids with metadata, return redis", "is None: fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx)", "@abc.abstractmethod def fetch(self, ids): \"\"\" hydrate relevant ids with data", "return redis pipeline that must be executed \"\"\" if fields", "redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\" hydrate", "obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj) return", "@abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod def", "for key, value in kwargs.items(): setattr(self, key, value) def fetch(self,", "Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies))", "super().__init__() for key, value in kwargs.items(): setattr(self, key, value) def", "Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def __init__(self, **kwargs):", "import LogMixin class Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self):", "__init__(self, **kwargs): super().__init__() for key, value in kwargs.items(): setattr(self, key,", "__metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\"", "hydrates class ids with metadata, return redis pipeline that must", "fields = Movies.DEFAULT_FIELDS if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx", "ids with metadata, return redis pipeline that must be executed", "from_index=False): \"\"\" hydrates class ids with metadata, return redis pipeline", "abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return @abc.abstractmethod", "if fields is None: fields = Movies.DEFAULT_FIELDS if from_index: movies", "values)) if 'genres' in obj: obj['genres'] = obj['genres'].split(',') if 'year'", "fields) obj = dict(zip(fields, values)) if 'genres' in obj: obj['genres']", "idx in movies)) response = [] for movie in movies:", "key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\" hydrates class", "[] for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj", "for movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj =", "if from_index: movies = self.redis.mget(('inverse:index:movie:{}'.format(idx) for idx in movies)) response", "= obj['genres'].split(',') if 'year' in obj: obj['year'] = int(obj['year']) response.append(obj)", "\"\"\" redis connection \"\"\" return @abc.abstractmethod def fetch(self, ids): \"\"\"", "kwargs.items(): setattr(self, key, value) def fetch(self, movies, fields=None, from_index=False): \"\"\"", "= abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection \"\"\" return", "that must be executed \"\"\" if fields is None: fields", "\"\"\" hydrate relevant ids with data \"\"\" return class Movies(Reponse,", "movie in movies: values = self.redis.hmget('movie:{}'.format(movie), fields) obj = dict(zip(fields,", "with metadata, return redis pipeline that must be executed \"\"\"", "return class Movies(Reponse, LogMixin): DEFAULT_FIELDS = ['title', 'year', 'genres'] def", "Reponse(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def redis(self): \"\"\" redis connection", "obj['year'] = int(obj['year']) response.append(obj) return response def movie_to_index(self, movies): return", "obj = dict(zip(fields, values)) if 'genres' in obj: obj['genres'] =" ]
[ "py_grpc_compile( name = name_pb, deps = deps, visibility = visibility,", "srcs = [name_pb], deps = all_requirements, # This magically adds", "\"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose", "native.py_library( name = name, srcs = [name_pb], deps = all_requirements,", "to PYTHONPATH imports = [name_pb], visibility = visibility, ) def", "= kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name =", ") native.py_library( name = name, srcs = [name_pb], deps =", "don't need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to", "= kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name =", "imports = [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name", "deps, visibility = visibility, verbose = verbose, ) native.py_library( name", "def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose =", "visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name", "kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile(", "+ \"_pb\" py_grpc_compile( name = name_pb, deps = deps, visibility", "visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\")", "name, srcs = [name_pb], deps = all_requirements, # This magically", "name_pb = name + \"_pb\" py_proto_compile( name = name_pb, deps", "= all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports", "\"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps =", "[name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\")", "name + \"_pb\" py_proto_compile( name = name_pb, deps = deps,", "visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name", "visibility, verbose = verbose, ) native.py_library( name = name, srcs", ") def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose", "name = name, srcs = [name_pb], deps = all_requirements, #", "= kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\"", "= name, srcs = [name_pb], deps = all_requirements, # This", "srcs = [name_pb], deps = all_requirements, # fixme don't need", "all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports =", "fixme don't need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb}", "visibility = visibility, verbose = verbose, ) native.py_library( name =", "\"py_proto_compile\", \"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps", "verbose = verbose, ) native.py_library( name = name, srcs =", "name_pb, deps = deps, visibility = visibility, verbose = verbose,", "This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility", "all_requirements, # fixme don't need grpc here # This magically", "= name + \"_pb\" py_grpc_compile( name = name_pb, deps =", "= name_pb, deps = deps, visibility = visibility, verbose =", "kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name", "py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\")", "[name_pb], deps = all_requirements, # fixme don't need grpc here", "def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose =", "\"_pb\" py_grpc_compile( name = name_pb, deps = deps, visibility =", "name + \"_pb\" py_grpc_compile( name = name_pb, deps = deps,", "name_pb = name + \"_pb\" py_grpc_compile( name = name_pb, deps", "need grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH", "= kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb =", "load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\")", "= visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps =", "= [name_pb], deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb}", "kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile(", "deps = all_requirements, # fixme don't need grpc here #", "adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility,", "\"_pb\" py_proto_compile( name = name_pb, deps = deps, visibility =", "py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\")", "# fixme don't need grpc here # This magically adds", "kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_proto_compile( name = name_pb,", "name, srcs = [name_pb], deps = all_requirements, # fixme don't", "deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH", "= [name_pb], deps = all_requirements, # fixme don't need grpc", "= name, srcs = [name_pb], deps = all_requirements, # fixme", "[name_pb], deps = all_requirements, # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to", "verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb = name +", "# This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb],", "deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\") name_pb", "visibility = visibility, ) def py_grpc_library(**kwargs): name = kwargs.get(\"name\") deps", "load(\"//python:compile.bzl\", \"py_proto_compile\", \"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name = kwargs.get(\"name\")", "kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility = kwargs.get(\"visibility\")", "name = name_pb, deps = deps, visibility = visibility, verbose", "deps = deps, visibility = visibility, verbose = verbose, )", "kwargs.get(\"visibility\") name_pb = name + \"_pb\" py_grpc_compile( name = name_pb,", "= name + \"_pb\" py_proto_compile( name = name_pb, deps =", "= all_requirements, # fixme don't need grpc here # This", "PYTHONPATH imports = [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs):", "= deps, visibility = visibility, verbose = verbose, ) native.py_library(", "= verbose, ) native.py_library( name = name, srcs = [name_pb],", "verbose, ) native.py_library( name = name, srcs = [name_pb], deps", "+ \"_pb\" py_proto_compile( name = name_pb, deps = deps, visibility", "<gh_stars>0 load(\"//python:compile.bzl\", \"py_proto_compile\", \"py_grpc_compile\") load(\"@grpc_py_deps//:requirements.bzl\", \"all_requirements\") def py_proto_library(**kwargs): name =", "= [name_pb], visibility = visibility, ) def py_grpc_library(**kwargs): name =", "= kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility =", "magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility =", "py_proto_compile( name = name_pb, deps = deps, visibility = visibility,", "name = kwargs.get(\"name\") deps = kwargs.get(\"deps\") verbose = kwargs.get(\"verbose\") visibility", "here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports =", "= visibility, verbose = verbose, ) native.py_library( name = name,", "REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports = [name_pb], visibility = visibility, )", "grpc here # This magically adds REPOSITORY_NAME/PACKAGE_NAME/{name_pb} to PYTHONPATH imports" ]
[ "else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" %", "USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED", "slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def", "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF", "THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY", "in the # documentation and/or other materials provided with the", "# # Redistribution and use in source and binary forms,", "ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import", "Copyright (c) 1999-2008 <NAME> and <NAME> # Copyright (c) 2009", "field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts", "the following conditions are # met: redistributions of source code", "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR", "Hewlett-Packard Development Company # All rights reserved. # # Redistribution", "in binary form must reproduce the above copyright # notice,", "without specific prior written permission. # # THIS SOFTWARE IS", "super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts def", "self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\"", "the new type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine)", "the type to it for field in self.field_asts: field.generate(new_type) self.symtab.popFrame()", "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT", "from # this software without specific prior written permission. #", "SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #", "FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT", "modification, are permitted provided that the following conditions are #", "list of conditions and the following disclaimer in the #", "NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND", "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH", "endorse or promote products derived from # this software without", "self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of", "import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts):", "redistributions in binary form must reproduce the above copyright #", "self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add", "self.symtab.state_machine # Make the new type new_type = Type(self.symtab, ident,", "source and binary forms, with or without # modification, are", "\"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast) machine =", "THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A", "the fields of the type to it for field in", "ANY WAY OUT OF THE USE # OF THIS SOFTWARE,", "ident = str(self.type_ast) machine = self.symtab.state_machine # Make the new", "LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING", "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER", "# neither the name of the copyright holders nor the", "# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS", "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO,", "SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR", "THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY", "(self.type_ast) def files(self, parent=None): if \"external\" in self: return set()", "and binary forms, with or without # modification, are permitted", "names of its # contributors may be used to endorse", "Add all of the fields of the type to it", "documentation and/or other materials provided with the distribution; # neither", "form must reproduce the above copyright # notice, this list", "USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE", "of the fields of the type to it for field", "machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields", "are # met: redistributions of source code must retain the", "copyright holders nor the names of its # contributors may", "if \"external\" in self: return set() if parent: ident =", "this software without specific prior written permission. # # THIS", "DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,", "TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY", "% (parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" %", "written permission. # # THIS SOFTWARE IS PROVIDED BY THE", "def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None):", "reproduce the above copyright # notice, this list of conditions", "software without specific prior written permission. # # THIS SOFTWARE", "OUT OF THE USE # OF THIS SOFTWARE, EVEN IF", "must retain the above copyright # notice, this list of", "# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #", "def files(self, parent=None): if \"external\" in self: return set() if", "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS", "and the following disclaimer; # redistributions in binary form must", "ident = self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident))", "return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if \"external\"", "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF", "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE", "machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of", "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE", "of source code must retain the above copyright # notice,", "slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast", "EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from", "# documentation and/or other materials provided with the distribution; #", "BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR", "def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast", "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF", "# this software without specific prior written permission. # #", "(c) 2009 The Hewlett-Packard Development Company # All rights reserved.", "OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE", "LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION)", "POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type", "and/or other materials provided with the distribution; # neither the", "pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts =", "or without # modification, are permitted provided that the following", "Redistribution and use in source and binary forms, with or", "the following disclaimer in the # documentation and/or other materials", "permitted provided that the following conditions are # met: redistributions", "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR", "retain the above copyright # notice, this list of conditions", "__init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast =", "HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER", "notice, this list of conditions and the following disclaimer; #", "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "rights reserved. # # Redistribution and use in source and", "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR", "binary form must reproduce the above copyright # notice, this", "IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS", "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #", "if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident", "ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED", "nor the names of its # contributors may be used", "ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() #", "<NAME> and <NAME> # Copyright (c) 2009 The Hewlett-Packard Development", "def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine # Make", "disclaimer in the # documentation and/or other materials provided with", "# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR", "DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE", "above copyright # notice, this list of conditions and the", "The Hewlett-Packard Development Company # All rights reserved. # #", "set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self): ident =", "2009 The Hewlett-Packard Development Company # All rights reserved. #", "Make the new type new_type = Type(self.symtab, ident, self.location, self.pairs,", "in source and binary forms, with or without # modification,", "TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs)", "the following disclaimer; # redistributions in binary form must reproduce", "# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,", "must reproduce the above copyright # notice, this list of", "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF", "products derived from # this software without specific prior written", "TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #", "1999-2008 <NAME> and <NAME> # Copyright (c) 2009 The Hewlett-Packard", "(INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS", "disclaimer; # redistributions in binary form must reproduce the above", "# redistributions in binary form must reproduce the above copyright", "that the following conditions are # met: redistributions of source", "OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY", "use in source and binary forms, with or without #", "self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast)", "WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN", "import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self,", "# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND", "IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR", "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED", "# contributors may be used to endorse or promote products", "materials provided with the distribution; # neither the name of", "parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident =", "= self.symtab.state_machine # Make the new type new_type = Type(self.symtab,", "machine = self.symtab.state_machine # Make the new type new_type =", "following disclaimer; # redistributions in binary form must reproduce the", "OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #", "OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED", "ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT", "provided with the distribution; # neither the name of the", "type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine:", "with or without # modification, are permitted provided that the", "EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO,", "from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST):", "# met: redistributions of source code must retain the above", "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,", "of the type to it for field in self.field_asts: field.generate(new_type)", "self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self):", "# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY", "holders nor the names of its # contributors may be", "OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE", "# notice, this list of conditions and the following disclaimer;", "IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT", "% ident)) def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine", "IN ANY WAY OUT OF THE USE # OF THIS", "CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,", "GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS;", "self: return set() if parent: ident = \"%s_%s\" % (parent,", "ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,", "prior written permission. # # THIS SOFTWARE IS PROVIDED BY", "CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL,", "type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\" %", "OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY", "CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE)", "and use in source and binary forms, with or without", "OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR", "return set() if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident)", "COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,", "and <NAME> # Copyright (c) 2009 The Hewlett-Packard Development Company", "OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT", "<NAME> # Copyright (c) 2009 The Hewlett-Packard Development Company #", "from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast,", "the copyright holders nor the names of its # contributors", "be used to endorse or promote products derived from #", "forms, with or without # modification, are permitted provided that", "ARISING IN ANY WAY OUT OF THE USE # OF", "parent=None): if \"external\" in self: return set() if parent: ident", "binary forms, with or without # modification, are permitted provided", "slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs,", "files(self, parent=None): if \"external\" in self: return set() if parent:", "\"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if \"external\" in", "copyright # notice, this list of conditions and the following", "specific prior written permission. # # THIS SOFTWARE IS PROVIDED", "contributors may be used to endorse or promote products derived", "DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR", "OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA,", "self.type_ast = type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl:", "__repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self, parent=None): if", "= str(self.type_ast) machine = self.symtab.state_machine # Make the new type", "the above copyright # notice, this list of conditions and", "COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS", "STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING", "redistributions of source code must retain the above copyright #", "fields of the type to it for field in self.field_asts:", "self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the fields of the", "# All rights reserved. # # Redistribution and use in", "of the copyright holders nor the names of its #", "Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame()", "BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY,", "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT", "Copyright (c) 2009 The Hewlett-Packard Development Company # All rights", "# Redistribution and use in source and binary forms, with", "INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF", "# Copyright (c) 2009 The Hewlett-Packard Development Company # All", "code must retain the above copyright # notice, this list", "self.symtab.pushFrame() # Add all of the fields of the type", "the # documentation and/or other materials provided with the distribution;", "IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS", "OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY", "FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO", "list of conditions and the following disclaimer; # redistributions in", "this list of conditions and the following disclaimer; # redistributions", "with the distribution; # neither the name of the copyright", "# modification, are permitted provided that the following conditions are", "SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS", "conditions and the following disclaimer in the # documentation and/or", "INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY,", "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE", "set() if parent: ident = \"%s_%s\" % (parent, self.type_ast.ident) else:", "self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts = field_asts def __repr__(self):", "may be used to endorse or promote products derived from", "neither the name of the copyright holders nor the names", "or promote products derived from # this software without specific", "NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE", "the distribution; # neither the name of the copyright holders", "of conditions and the following disclaimer in the # documentation", "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE", "EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE", "DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type class", "INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT", "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #", "INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT", "# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,", "HOLDERS AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR", "the names of its # contributors may be used to", "# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND", "type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc, pairs) self.type_ast = type_ast self.field_asts", "promote products derived from # this software without specific prior", "of conditions and the following disclaimer; # redistributions in binary", "= type_ast self.field_asts = field_asts def __repr__(self): return \"[TypeDecl: %r]\"", "PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #", "all of the fields of the type to it for", "(c) 1999-2008 <NAME> and <NAME> # Copyright (c) 2009 The", "DeclAST from slicc.symbols.Type import Type class TypeDeclAST(DeclAST): def __init__(self, slicc,", "str(self.type_ast) machine = self.symtab.state_machine # Make the new type new_type", "notice, this list of conditions and the following disclaimer in", "= self.type_ast.ident return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def", "PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #", "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST", "Development Company # All rights reserved. # # Redistribution and", "All rights reserved. # # Redistribution and use in source", "% ident, \"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast)", "without # modification, are permitted provided that the following conditions", "conditions are # met: redistributions of source code must retain", "\"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\"", "field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def files(self,", "# notice, this list of conditions and the following disclaimer", "following conditions are # met: redistributions of source code must", "this list of conditions and the following disclaimer in the", "used to endorse or promote products derived from # this", "AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN", "THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF", "IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED", "MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED.", "ident = \"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident", "reserved. # # Redistribution and use in source and binary", "CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN", "# Add all of the fields of the type to", "# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS", "BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY", "ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES", "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON", "distribution; # neither the name of the copyright holders nor", "# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL", "conditions and the following disclaimer; # redistributions in binary form", "OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import", "= Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type)", "WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES", "AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT,", "# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS", "\"external\" in self: return set() if parent: ident = \"%s_%s\"", "pairs) self.type_ast = type_ast self.field_asts = field_asts def __repr__(self): return", "new type new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if", "TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,", "provided that the following conditions are # met: redistributions of", "OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #", "name of the copyright holders nor the names of its", "ident, \"%s.cc\" % ident)) def generate(self): ident = str(self.type_ast) machine", "LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN", "the name of the copyright holders nor the names of", "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR", "other materials provided with the distribution; # neither the name", "permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT", "OF THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST", "are permitted provided that the following conditions are # met:", "AND CONTRIBUTORS # \"AS IS\" AND ANY EXPRESS OR IMPLIED", "# Make the new type new_type = Type(self.symtab, ident, self.location,", "if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all of the", "= \"%s_%s\" % (parent, self.type_ast.ident) else: ident = self.type_ast.ident return", "BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\" AND", "% (self.type_ast) def files(self, parent=None): if \"external\" in self: return", "to endorse or promote products derived from # this software", "%r]\" % (self.type_ast) def files(self, parent=None): if \"external\" in self:", "new_type = Type(self.symtab, ident, self.location, self.pairs, self.state_machine) if machine: machine.addType(new_type)", "(parent, self.type_ast.ident) else: ident = self.type_ast.ident return set((\"%s.hh\" % ident,", "SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from slicc.symbols.Type import Type", "NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;", "= field_asts def __repr__(self): return \"[TypeDecl: %r]\" % (self.type_ast) def", "its # contributors may be used to endorse or promote", "in self: return set() if parent: ident = \"%s_%s\" %", "# Copyright (c) 1999-2008 <NAME> and <NAME> # Copyright (c)", "OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER", "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #", "source code must retain the above copyright # notice, this", "of its # contributors may be used to endorse or", "Company # All rights reserved. # # Redistribution and use", "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF", "# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT", "ident)) def generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine #", "following disclaimer in the # documentation and/or other materials provided", "class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST, self).__init__(slicc,", "NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE", "derived from # this software without specific prior written permission.", "Type class TypeDeclAST(DeclAST): def __init__(self, slicc, type_ast, pairs, field_asts): super(TypeDeclAST,", "THE POSSIBILITY OF SUCH DAMAGE. from slicc.ast.DeclAST import DeclAST from", "generate(self): ident = str(self.type_ast) machine = self.symtab.state_machine # Make the", "FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL", "return set((\"%s.hh\" % ident, \"%s.cc\" % ident)) def generate(self): ident", "PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # \"AS IS\"", "self.pairs, self.state_machine) if machine: machine.addType(new_type) self.symtab.newSymbol(new_type) self.symtab.pushFrame() # Add all", "met: redistributions of source code must retain the above copyright", "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT", "and the following disclaimer in the # documentation and/or other" ]